datetime.datetime.fromtimestamp
will do, if you know the time zone, you could produce the same output as with time.gmtime
>>> datetime.datetime.fromtimestamp(1284286794)
datetime.datetime(2010, 9, 12, 11, 19, 54)
or
>>> datetime.datetime.utcfromtimestamp(1284286794)
datetime.datetime(2010, 9, 12, 10, 19, 54)
Seconds since epoch to datetime
to strftime
:
>>> ts_epoch = 1362301382
>>> ts = datetime.datetime.fromtimestamp(ts_epoch).strftime('%Y-%m-%d %H:%M:%S')
>>> ts
'2013-03-03 01:03:02'
From the docs, the recommended way of getting a timezone aware datetime object from seconds since epoch is:
Python 3:
from datetime import datetime, timezone
datetime.fromtimestamp(timestamp, timezone.utc)
Python 2, using pytz
:
from datetime import datetime
import pytz
datetime.fromtimestamp(timestamp, pytz.utc)
Note that datetime.datetime.fromtimestamp(timestamp) and .utcfromtimestamp(timestamp) fail on windows for dates before Jan. 1, 1970 while negative unix timestamps seem to work on unix-based platforms. The docs say this:
See also Issue1646728
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