python linux timestamp to date time and reverse

sanjayan ravi picture sanjayan ravi · Apr 24, 2013 · Viewed 11.3k times · Source

i would like to know how to convert datetime Wed Apr 24 19:25:06 2013 GMT into Linux timestamp 1366831506000 (13 digits)] and reverse using python.

for example:

Wed Apr 24 19:25:06 2013 GMT

to

1366831506000

and from

1366831506000

to

Wed Apr 24 19:25:06 2013 GMT

Answer

Martijn Pieters picture Martijn Pieters · Apr 24, 2013

From string to timestamp, use time.strptime(), passing the resulting struct_time tuple to time.mktime(); your timestamp uses milliseconds, not the UNIX seconds-as-floating-point value, so you need to multiply by 1000:

import time

datestr = "Wed Apr 24 19:25:06 2013 GMT"
time.mktime(time.strptime(datestr, "%a %b %d %H:%M:%S %Y %Z")) * 1000

In the other direction, use time.strptime(), passing in a struct_time tuple created by time.gmtime(), dividing the timestamp by 1000 first:

timestamp = 1366831506000
time.strftime("%a %d %b %Y %H:%M:%S GMT", time.gmtime(timestamp / 1000.0))

Demo:

>>> datestr = "Wed Apr 24 19:25:06 2013 GMT"
>>> time.mktime(time.strptime(datestr, "%a %b %d %H:%M:%S %Y %Z")) * 1000
1366827906000.0
>>> timestamp = 1366831506000
>>> time.strftime("%a %d %b %Y %H:%M:%S GMT", time.gmtime(timestamp / 1000.0))
'Wed 24 Apr 2013 19:25:06 GMT'