开发者

Convert date retrieved from ntp server with python

开发者 https://www.devze.com 2023-03-19 15:27 出处:网络
Is it possible to convert time retrieved from NTP server(with python script) in this format \"Wed Jul 13 00:17:58 CEST 2011\" to this format \"2011-07-13 00:18:10\"

Is it possible to convert time retrieved from NTP server (with python script) in this format "Wed Jul 13 00:17:58 CEST 2011" to this format "2011-07-13 00:18:10"

    client = socket(AF_INET, SOCK_DGRAM)
    data = '\x1b' + 47 * '\0'
    client.sendto(data, (ntp.server.com,123))
    data, address = client.recvfrom( 开发者_如何学编程1024 )
    if data:
        utc_secs = struct.unpack('!12I', data)[10]
        utc_secs -= 2208988800L
        utc_secs = time.ctime(utc_secs)
        print utc_secs
        return utc_secs

I get this format : "Wed Jul 13 00:17:58 CEST 2011"

I want to convert this into this format "2011-07-13 00:17:58" ( '%Y-%m-%d %H:%M:%S' )

Thanks :)


In your case you can go directly from the number of seconds to the time format you desire; however I will explain the general solution before the exact snippet for your case at the bottom.

In general this type of problem is solved with the help of strptime and strftime. You should also refer to the formatting codes in the python docs.

strptime() matches the pieces of a date string and creates a python time structure. strftime() can then be used to convert that time structure into whatever format you desire.

from datetime import datetime
ntp_time = datetime.strptime(time_str_from_ntp, "%a %b %y %H:%M:%S")
formatted_time = datetime.strftime(ntp_time, "%Y-%m-%d %H:%M:%S")

Or in your particular case, you can replace

utc_secs = time.ctime(utc_secs)

with (NOTE: if you have not done from datetime import datetime then you should use datetime.datetime.fromtimestamp below and not simply datetime.fromtimestamp)

formatted_time = datetime.fromtimestamp(utc_secs).strftime("%Y-%m-%d %H:%M:%S")


>>> sec #your utc_secs
1310511730
>>> time.ctime(sec) #instead of this
'Wed Jul 13 02:02:10 2011'
>>> d = datetime.datetime.fromtimestamp(sec) #do this
>>> d   
datetime.datetime(2011, 7, 13, 2, 2, 10)
>>> d.strftime('%Y-%m-%d %H:%M:%S')
'2011-07-13 02:02:10'
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号