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
You can simply use the fromtimestamp function from the DateTime module to get a date from a UNIX timestamp. This function takes the timestamp as input and returns the corresponding DateTime object to timestamp.
Getting the UTC timestamp Use the datetime. datetime. now() to get the current date and time. Then use tzinfo class to convert our datetime to UTC.
The strftime() method can be used to create formatted strings.
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With