I have a string representing a unix timestamp (i.e. "1284101485") in Python, and I'd like to convert it to a readable date. When I use time.strftime
, I get a TypeError
:
>>>import time
>>>print time.strftime("%B %d %Y", "1284101485")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: argument must be 9-item sequence, not str
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:
Where posix_time is the Posix epoch time you want to convert
Get the readable date from timestamp with time also, also you can change the format of the date.
There are two parts:
A portable way to get the local time that works even if the local time zone had a different utc offset in the past and python has no access to the tz database is to use a
pytz
timezone:To display it, you could use any time format that is supported by your system e.g.:
If you do not need a local time, to get a readable UTC time instead:
If you don't care about the timezone issues that might affect what date is returned or if python has access to the tz database on your system:
On Python 3, you could get a timezone-aware datetime using only stdlib (the UTC offset may be wrong if python has no access to the tz database on your system e.g., on Windows):
Functions from the
time
module are thin wrappers around the corresponding C API and therefore they may be less portable than the correspondingdatetime
methods otherwise you could use them too:There is an interesting way where you do not have to worry about the time zones, utc, etc. Simply convert the string into Excel date format, and then to a readable date/time: