Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert timestamp since epoch to datetime.datetime

Tags:

python

I have the following timestamps since epoch:

Timestamp 1346114717972 1354087827000 

How can I convert these timestamps to some specific output format, e.g., mm/dd/yyyy hr:min:sec?

I have tried to convert them to datetime.datetime but it failed:

 >>> datetime.datetime.fromtimestamp(1346114717972)  Traceback (most recent call last):  File "<stdin>", line 1, in <module>  ValueError: timestamp out of range for platform time_t 

How can I do this?

like image 409
Rajeev Avatar asked Sep 17 '12 11:09

Rajeev


People also ask

How do I convert epoch time to normal date?

Convert from epoch to human-readable dateString date = new java.text.SimpleDateFormat("MM/dd/yyyy HH:mm:ss").format(new java.util.Date (epoch*1000)); Epoch in seconds, remove '*1000' for milliseconds. myString := DateTimeToStr(UnixToDateTime(Epoch)); Where Epoch is a signed integer. Replace 1526357743 with epoch.

How do you convert datetime to seconds since epoch?

To convert a datetime to seconds, subtracts the input datetime from the epoch time. For Python, the epoch time starts at 00:00:00 UTC on 1 January 1970. Subtraction gives you the timedelta object. Use the total_seconds() method of a timedelta object to get the number of seconds since the epoch.

How is epoch time date calculated?

Multiply the two dates' absolute difference by 86400 to get the Epoch Time in seconds – using the example dates above, is 319080600.


1 Answers

I would use the time module

>>> import time >>> time.gmtime(1346114717972/1000.) time.struct_time(tm_year=2012, tm_mon=8, tm_mday=28, tm_hour=0, tm_min=45, tm_sec=17, tm_wday=1, tm_yday=241, tm_isdst=0)   

This shows the timestamp in UTC/GMT time.

The timestamp is divided by 1000 as the stamps you have provided are in milliseconds since the epoch, not seconds.

Then use strftime to format like so:

>>> time.strftime('%m/%d/%Y %H:%M:%S',  time.gmtime(1346114717972/1000.)) '08/28/2012 00:45:17' 
like image 164
olly_uk Avatar answered Oct 05 '22 22:10

olly_uk