Converting to UTC time

Trey Hunner smiling in a t-shirt against a yellow wall
Trey Hunner
1 min. read Python 3.7—3.11
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

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)

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)

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.