Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 do

from datetime import datetime
from zoneinfo import ZoneInfo

naive = datetime(2020, 6, 11, 12)
aware = naive.replace(tzinfo=ZoneInfo('localtime'))

but on Windows, that throws

ZoneInfoNotFoundError: 'No time zone found with key localtime'

so would I still have to use a third-party library? e.g.

import time
import dateutil

tzloc = dateutil.tz.gettz(time.tzname[time.daylight])
aware = naive.replace(tzinfo=tzloc)

Since time.tzname[time.daylight] returns a localized name (German in my case, e.g. 'Mitteleuropäische Sommerzeit'), this doesn't work either:

aware = naive.replace(tzinfo=ZoneInfo(tzloc))

Any thoughts?


p.s. to try this on Python < 3.9, use backports (see also this answer):

pip install backports.zoneinfo
pip install tzdata # needed on Windows
like image 312
FObersteiner Avatar asked Jun 11 '20 18:06

FObersteiner


People also ask

How do you get different time zones in Python?

Use the datetime. astimezone() method to convert the datetime from one timezone to another. This method uses an instance of the datetime object and returns a new datetime of a given timezone.

Which Python library is used for timezone?

pytz brings the Olson tz database into Python. This library allows accurate and cross platform timezone calculations using Python 2.4 or higher. It also solves the issue of ambiguous times at the end of daylight saving time, which you can read more about in the Python Library Reference ( datetime. tzinfo ).


2 Answers

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()
like image 173
Matt Johnson-Pint Avatar answered Oct 09 '22 17:10

Matt Johnson-Pint


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')
like image 43
FObersteiner Avatar answered Oct 09 '22 17:10

FObersteiner