python – Converting unix timestamp string to readable date

python – Converting unix timestamp string to readable date

Use datetime module:

from datetime import datetime
ts = int(1284101485)

# if you encounter a year is out of range error the timestamp
# may be in milliseconds, try `ts /= 1000` in that case
print(datetime.utcfromtimestamp(ts).strftime(%Y-%m-%d %H:%M:%S))
>>> from datetime import datetime
>>> datetime.fromtimestamp(1172969203.1)
datetime.datetime(2007, 3, 4, 0, 46, 43, 100000)

Taken from http://seehuhn.de/pages/pdate

python – Converting unix timestamp string to readable date

The most voted answer suggests using fromtimestamp which is error prone since it uses the local timezone. To avoid issues a better approach is to use UTC:

datetime.datetime.utcfromtimestamp(posix_time).strftime(%Y-%m-%dT%H:%M:%SZ)

Where posix_time is the Posix epoch time you want to convert

Leave a Reply

Your email address will not be published. Required fields are marked *