Open In App

Convert Datetime to UTC Timestamp in Python

Last Updated : 01 Jul, 2025
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

Converting a Datetime to a UTC Timestamp in Python means transforming a date and time into the number of seconds since the Unix epoch (January 1, 1970, UTC), while correctly accounting for time zones. For example, converting January 25, 2024, 12:00 PM UTC to a timestamp would yield 1706184000.0. Let's explore different methods to do this efficiently.

Using datetime.timestamp()

This method attaches the UTC timezone to a naive datetime object using replace(tzinfo=timezone.utc) and then calls .timestamp() to get the UTC timestamp. This is the most recommended and modern approach for converting to a UTC timestamp.

Python
from datetime import datetime, timezone
dt = datetime(2024, 1, 25, 12, 0, 0)
res = dt.replace(tzinfo=timezone.utc).timestamp()
print(res)

Output
1706184000.0

Explanation: A naive datetime for January 25, 2024, at 12:00 PM is created without timezone info. replace(tzinfo=timezone.utc) makes it UTC-aware and .timestamp() returns the correct Unix timestamp.

Using calendar.timegm()

In this method, the datetime is converted to a UTC time tuple using .utctimetuple() and then calendar.timegm() computes the timestamp. It’s best suited for naive datetime objects that represent UTC.

Python
import calendar
from datetime import datetime

dt = datetime(2024, 1, 25, 12, 0, 0)
res = calendar.timegm(dt.utctimetuple())
print(res)

Output
1706184000

Explanation: A naive datetime for January 25, 2024, 12:00 PM is treated as UTC. utctimetuple() converts it to a UTC tuple and calendar.timegm() returns the Unix timestamp.

Using pytz.utc.localize()

This method uses the pytz library to localize a naive datetime to UTC, then converts it using .timestamp(). It's useful for multi-timezone applications and ensures accurate timezone handling, though it requires an external library.

Python
import pytz
from datetime import datetime

dt = datetime(2024, 1, 25, 12, 0, 0)
dt_utc = pytz.utc.localize(dt)

res = dt_utc.timestamp()
print(res)

Output
1706184000.0

Explanation: A naive datetime for January 25, 2024, at 12:00 PM is created. pytz.utc.localize(dt) makes it UTC-aware and .timestamp() returns the seconds since the Unix epoch.

Using time.mktime()

time.mktime() method converts a datetime to a timestamp based on local time, not UTC. It’s simple and uses dt.timetuple(), but isn't reliable for UTC conversions and should be used only for local timestamps.

Python
import time
from datetime import datetime

dt = datetime(2024, 1, 25, 12, 0, 0)
res = time.mktime(dt.timetuple())
print(res)

Output
1706184000.0

Explanation: dt.timetuple() creates a time tuple and time.mktime() returns the timestamp based on local time. Though simple and built-in, it’s unreliable for UTC conversions if local time differs from UTC.

Related articles


Next Article

Similar Reads