Explain Codes LogoExplain Codes Logo

Convert datetime to Unix timestamp and convert it back in python

python
datetime
unix-timestamp
timezone-aware
Anton ShumikhinbyAnton Shumikhin·Feb 2, 2025
TLDR

To convert a datetime to a Unix timestamp we use the timestamp() method. To convert back, we can use fromtimestamp():

from datetime import datetime # Conversion to Unix timestamp dt_to_unix = datetime.now().timestamp() # Conversion back to datetime unix_to_dt = datetime.fromtimestamp(dt_to_unix)

Handling timezones in conversion

When dealing with different timezones, it's essential to use timezone-aware datetime objects to avoid any potential mismatches or errors:

from datetime import datetime, timezone # Datetime with UTC timezone dt_utc_aware = datetime.now(timezone.utc) # Conversion to Unix timestamp unix_timestamp = dt_utc_aware.timestamp() # Conversion back to datetime aware_unix_to_dt = datetime.fromtimestamp(unix_timestamp, timezone.utc)

Now every time your timestamp travels abroad, it can tell exactly what time it is back home!

Counting seconds since epoch

If you're nostalgic about the good old days of 1970, you can use total_seconds() and calculate the number of seconds since the epoch:

from datetime import datetime, timedelta # timedelta since the epoch td_since_epoch = datetime.now() - datetime(1970, 1, 1) # Total seconds since epoch total_seconds = td_since_epoch.total_seconds() # Datetime from total seconds datetime_from_seconds = datetime(1970, 1, 1) + timedelta(seconds=total_seconds)

We're talking about ~1.6 trillion seconds since the epoch. Yeah, time flies!

On daylight saving time

When handling local times and Unix timestamps, potential shifts due to daylight saving time (DST) changes need to be considered:

import time from datetime import datetime, timezone local_dt = datetime(2023, 3, 8, 12, 0) # A date before DST change unix_timestamp_before_dst = time.mktime(local_dt.timetuple()) reverted_dt_before_dst = datetime.fromtimestamp(unix_timestamp_before_dst, timezone.utc) local_dt_after_dst = datetime(2023, 3, 9, 12, 0) # A date after DST change unix_timestamp_after_dst = time.mktime(local_dt_after_dst.timetuple()) reverted_dt_after_dst = datetime.fromtimestamp(unix_timestamp_after_dst, timezone.utc)

That's right, even your code needs to remember to spring forward and fall back on DST shifts!

Attention to platform specifics

Remember, not all platforms are created equal. For instance, using strftime('%s') to obtain the seconds since epoch may not yield correct results on some of them:

from datetime import datetime # The way below may not be consistent across platforms # seconds_since_epoch_str = datetime.now().strftime('%s') # Instead, use this for a safer ride seconds_since_epoch = datetime.now().timestamp()

So, make sure you check the compatibility of your platform with this magic '%s' spell before casting it!