Converting datetime to UTC in Python

Trey Hunner smiling in a t-shirt against a yellow wall
Trey Hunner
1 min. read Python 3.8—3.12
Share
Copied to clipboard.

Let's say we have a datetime.datetime object representing a specific time (in our machine's local time zone).

>>> import datetime
>>> april_fools = datetime.datetime(2030, 4, 1, 10, 0)

That april_fools variable points to a datetime object representing 10am or April 1, 2030 (in our local timezone):

>>> april_fools
datetime.datetime(2030, 4, 1, 10, 0)

Converting a time to UTC in Python

To convert this time to UTC we can use the astimezone method on our datetime.datetime object:

>>> utc_april_fools = april_fools.astimezone(datetime.timezone.utc)
>>> utc_april_fools
datetime.datetime(2030, 4, 1, 17, 0, tzinfo=datetime.timezone.utc)
>>> print(utc_april_fools)
2030-04-01 17:00:00+00:00

Or on Python 3.11+ you can use datetime.UTC instead of datetime.timezone.utc:

>>> utc_april_fools = april_fools.astimezone(datetime.UTC)
>>> utc_april_fools
datetime.datetime(2030, 4, 1, 17, 0, tzinfo=datetime.UTC)
>>> print(utc_april_fools)
2030-04-01 17:00:00+00:00

Getting the current time in UTC

What if we want to convert the current time to UTC?

While Python's datetime objects do have a utcnow method:

>>> datetime.datetime.utcnow()
datetime.datetime(2030, 4, 1, 8, 15, 59, 89013)

This method was deprecated in Python 3.12 and the Python documentation recommends passing the target timezone (timezone.utc in our case) to the now method instead:

>>> datetime.datetime.now(datetime.timezone.utc)
datetime.datetime(2030, 4, 1, 8, 15, 59, 89013, tzinfo=datetime.timezone.utc)

Or on Python 3.11+:

>>> datetime.datetime.now(datetime.UTC)
datetime.datetime(2030, 4, 1, 8, 15, 59, 89013, tzinfo=datetime.timezone.utc)

That way you'll end up with a timezone-aware datetime object (see naive and aware objects for more on timezone awareness).

A Python Tip Every Week

Need to fill-in gaps in your Python skills? I send weekly emails designed to do just that.