Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

datetime - 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 timezone (OS setting) on Windows.

On 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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...