Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python linux timestamp to date time and reverse [closed]

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
like image 872
sanjayan ravi Avatar asked Apr 24 '13 17:04

sanjayan ravi


People also ask

How do I convert a timestamp to a date in Python?

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.

How do I convert UTC timestamp to date in Python?

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.

How do I convert a timestamp to a string in Python?

The strftime() method can be used to create formatted strings.


1 Answers

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'
like image 95
Martijn Pieters Avatar answered Sep 23 '22 16:09

Martijn Pieters