Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert date retrieved from ntp server with python

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 :)

like image 340
rapidshell Avatar asked Oct 10 '22 13:10

rapidshell


2 Answers

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")
like image 180
shelhamer Avatar answered Oct 13 '22 05:10

shelhamer


>>> 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'
like image 32
utdemir Avatar answered Oct 13 '22 06:10

utdemir