How do I get a value of in Python that is timezone aware?

How do I get a value of in Python that is timezone aware?

In the standard library, there is no cross-platform way to create aware timezones without creating your own timezone class. (Edit: Python 3.9 introduces zoneinfo in the standard library which does provide this functionality.)

On Windows, theres win32timezone.utcnow(), but thats part of pywin32. I would rather suggest to use the pytz library, which has a constantly updated database of most timezones.

Working with local timezones can be very tricky (see Further reading links below), so you may rather want to use UTC throughout your application, especially for arithmetic operations like calculating the difference between two time points.

You can get the current date/time like so:

import pytz
from datetime import datetime

Mind that and return the local time, not the UTC time, so applying .replace(tzinfo=pytz.utc) to them would not be correct.

Another nice way to do it is:

which is a bit shorter and does the same.

Further reading/watching why to prefer UTC in many cases:

Get the current time, in a specific timezone:

import datetime
import pytz
my_date =

Remember to install pytz first.

How do I get a value of in Python that is timezone aware?

In Python 3.2+: datetime.timezone.utc:

The standard library makes it much easier to specify UTC as the time zone:

>>> import datetime
datetime.datetime(2020, 11, 27, 14, 34, 34, 74823, tzinfo=datetime.timezone.utc)

You can also get a datetime that includes the local time offset using astimezone:

datetime.datetime(2020, 11, 27, 15, 34, 34, 74823, tzinfo=datetime.timezone(datetime.timedelta(seconds=3600), CET))

(In Python 3.6+, you can shorten the last line to:

If you want a solution that uses only the standard library and that works in both Python 2 and Python 3, see jfs answer.

In Python 3.9+: zoneinfo to use the IANA time zone database:

In Python 3.9, you can specify particular time zones using the standard library, using zoneinfo, like this:

>>> from zoneinfo import ZoneInfo
datetime.datetime(2020, 11, 27, 6, 34, 34, 74823, tzinfo=zoneinfo.ZoneInfo(key=America/Los_Angeles))

zoneinfo gets its database of time zones from the operating system, or from the first-party PyPI package tzdata if available.

Leave a Reply

Your email address will not be published. Required fields are marked *