In Python, how do you convert seconds since epoch to a datetime
object?
To swiftly convert the epoch time to a datetime
in Python, simply use:
Don't forget to replace 1633076672
with your actual timestamp.
However, things can get a little tricky when dealing with different time zones. Fear not, here's how to convert it correctly for local time or UTC.
Converting in different time zones and UTC
When dealing with time zones, transform your timestamp for the correct local time or UTC:
For strict UTC time, use utcfromtimestamp()
:
Remember, if you're dealing with dates before 1970 on Windows (where epoch times were still a glimmer in Ken Thompson's eye), stick with utcfromtimestamp
.
Formatting the datetime monster
Done with conversion? Great! Now let's polish the datetime
object for readability. Use the strftime()
method:
Prettier now, isn't it?
Dealing with outliers
Here are a few heads-ups when working with timestamps:
-
Negative epochs: Unix can take it, but Windows might give you the cold shoulder.
-
ISO 8601 format: Use
isoformat()
– because even robots need standards. -
Platform-specific issues: Always have this in mind. An Apple a day keeps the doctor away, but Microsoft might still give you headaches.
Pitfall alert! Watch out for the ValueError
Some timestamps can be out of the range of values supported by the platform's datetime
library, and using fromtimestamp
might raise a ValueError
. Always have a try...except
safety net.
Working secret gears: Python 2 & peeping into extra libraries
Python 2 compatibility
The menacing compatibility issues with Python 2 can be pacified using the pytz
library for timezone conversions:
Helper libraries at your service
There's a whole cavalry of third-party libraries like Arrow
and dateutil
for easy handling of dates and times:
And always remember to import those modules (datetime
, timezone
, pytz
...), or the Python interpreter might act like a doorman keeping you out of your own party.
Was this article helpful?