Convert python datetime to epoch with strftime
Instantly convert a datetime
object to epoch seconds with this handy snippet:
Call timestamp()
on a datetime
object to get the epoch time. Don't forget, dt
needs replacing with your own datetime
object.
Python signpost: 3.3 or an earlier version
If you're stuck in the past using a Python version prior to 3.3, datetime.timestamp()
won't be in your toolkit. Instead, you can calculate the total number of seconds since the Unix epoch like so:
Journey to the center of timezones
Universal Time, not Cuckoo Time (UTC!)
Make sure you're on calendar.timegm()
especially if you need to work with UTC time when converting epoch:
Dialing Local Time
If your local timezone is integral to your epoch conversion, use the following approach:
Don't forget time.mktime()
uses your local timezone, so do change your datetime to UTC before using this method when necessary.
Precision is key – not just in locksmithing
Classy Microseconds
To bring microseconds into your epoch conversion for more precise measuring:
Things to jot down
The Pythonic scroll of wisdom
Always have a look at the Python documentation regarding strftime
- it's better to consult the scrolls of wisdom before embarking on your time travel journey.
Sync your watches
Consider system time settings and how they could impact your epoch conversion. Nothing can derail a good time travel plan more than a misaligned clock!
Was this article helpful?