Skip to content Skip to sidebar Skip to footer

Get Local Time Zone Name On Windows (python 3.9 Zoneinfo)

Checking out the zoneinfo module in Python 3.9, I was wondering if it also offers a convenient option to retrieve the local time zone (OS setting) on Windows. On GNU/Linux, you can

Solution 1:

You don't need to use zoneinfo to use the system local time zone. You can simply pass None (or omit) the time zone when calling datetime.astimezone.

From the docs:

If called without arguments (or with tz=None) the system local timezone is assumed. The .tzinfo attribute of the converted datetime instance will be set to an instance of timezone with the zone name and offset obtained from the OS.

Thus:

from datetime import datetime

naive = datetime(2020, 6, 11, 12)
aware = naive.astimezone()

Solution 2:

While astimezone(None) is convenient, sometimes you might want to get the IANA name of your time zone, not what Windows thinks is best for you.

The new version 4.1 of tzlocal will also use zoneinfo for that whilst maintaining compatibility with pytz through the deprecation shim:

>>>import tzlocal>>>print(tzlocal.get_localzone())
Europe/Berlin
>>>print(repr(tzlocal.get_localzone()))
_PytzShimTimezone(zoneinfo.ZoneInfo(key='Europe/Berlin'), 'Europe/Berlin')

Post a Comment for "Get Local Time Zone Name On Windows (python 3.9 Zoneinfo)"