Explain Codes LogoExplain Codes Logo

Convert python datetime to epoch with strftime

python
datetime
timestamp
epoch
Nikita BarsukovbyNikita Barsukov·Feb 3, 2025
TLDR

Instantly convert a datetime object to epoch seconds with this handy snippet:

from datetime import datetime # Pick your date or time; cue invisible flux capacitor... dt = datetime(2023, 1, 1) epoch = int(dt.timestamp()) print(epoch) # Just like Doc Brown, you've got time in your hands!

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:

from datetime import datetime # Once again, choose your date or time... dt = datetime(2023, 1, 1) epoch = (dt - datetime(1970, 1, 1)).total_seconds() print(int(epoch)) # Witness epoch rise from the ashes of time!

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:

import calendar from datetime import datetime # Get current UTC datetime dt = datetime.utcnow() # Timezone madness begone! epoch = calendar.timegm(dt.utctimetuple()) print(epoch) # Now that's some Universal Time magic!

Dialing Local Time

If your local timezone is integral to your epoch conversion, use the following approach:

import time from datetime import datetime dt = datetime.now() # Let's go......now! epoch = int(time.mktime(dt.timetuple())) print(epoch) # Time is an illusion, lunchtime doubly so!

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:

from datetime import datetime dt = datetime.now() # That's NOW now! epoch_with_microseconds = time.mktime(dt.timetuple()) + (dt.microsecond * 1e-6) print(epoch_with_microseconds) # Yeah, we've got time for microseconds!

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!