How do I convert a datetime to a UTC timestamp in Python?


You can use the datetime module to convert a datetime to a UTC timestamp in Python. If you already have the datetime object in UTC, you can the timestamp() to get a UTC timestamp. This function returns the time since epoch for that datetime object. If you have the datetime object in local timezone, first replace the timezone info and then fetch the time. 

example

from datetime import timezone
dt = datetime(2015, 10, 19)
timestamp = dt.replace(tzinfo=timezone.utc).timestamp()
print(timestamp)

Output

This will give the output −

1445212800.0

If you're on Python 2, then you can use the total_seconds() function to get the total seconds since epoch. And if you want to get rid of the timestamp, you can first subtract time from 1 Jan 1970. 

example

from datetime import timezone
dt = datetime(2015, 10, 19)
timestamp = (dt - datetime(1970, 1, 1)).total_seconds()
print(timestamp)

Output

This will give the output −

1445212800.0

Updated on: 26-Aug-2023

30K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements