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)
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
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).
Need to fill-in gaps in your Python skills?
Sign up for my Python newsletter where I share one of my favorite Python tips every week.
Need to fill-in gaps in your Python skills? I send weekly emails designed to do just that.