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
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.
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 ).
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()
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With