Convert timestamp since epoch to datetime.datetime
Asked Answered
A

3

61

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?

Arian answered 17/9, 2012 at 11:50 Comment(1)
What you did is correct, just that you're passing milliseconds not seconds. Try datetime.datetime.fromtimestamp(1346114717972/1000)Life
B
74

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'
Beaulieu answered 17/9, 2012 at 11:58 Comment(3)
Phew ... I was assuming seconds so and I calculated that was something like 42685 years since the epoch and I was thinking that something had to be wrong there...Chancellorsville
maybe using 1e3 instead of 1000. is betterKlutz
@Klutz It's the same, right? They are the same float values. But sure, if somebody have forgotten the dot after the 1000 in Python 2, then it was an integer division, and there can be at most one second difference. But it is not the case any more in Python 3.Pituitary
N
62

Assuming millisecond resolution:

import datetime

s = '1346114717972'
fmt = "%Y-%m-%d %H:%M:%S"

# local time
t = datetime.datetime.fromtimestamp(float(s)/1000.)
print t.strftime(fmt) # prints 2012-08-28 02:45:17

# utc time
t_utc = datetime.datetime.utcfromtimestamp(float(s)/1000.)
print t_utc.strftime(fmt) # prints 2012-08-28 00:45:17

Have a look at the documentation for the strftime() and strptime() behavior.

Niece answered 17/9, 2012 at 12:3 Comment(1)
Note that this answer will convert the timestamp to a local datetime. If you want the equivalent datetime in UTC use datetime.datetime.utcfromtimestamp() instead of datetime.datetime.fromtimestamp().Fendig
B
5

This is the simplest method I've ever seen-

$ python
Python 2.7.5 (default, Nov  6 2016, 00:28:07) 
[GCC 4.8.5 20150623 (Red Hat 4.8.5-11)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import time
>>> print(time.strftime('%Y-%m-%dT%H:%M:%S %Z',time.localtime(time.time())))
2018-05-02T13:21:44 IST
Badminton answered 2/5, 2018 at 7:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.