在Windows上获取本地时区名称(Python 3.9 zoneinfo) [英] Get local time zone name on Windows (Python 3.9 zoneinfo)

查看:341
本文介绍了在Windows上获取本地时区名称(Python 3.9 zoneinfo)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

查看 zoneinfo Python 3.9中的模块,我想知道它是否还提供了一个方便的选项来检索Windows上的本地时区(操作系统设置).

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.

在Linux上,您可以这样做

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

但是在Windows上会抛出

but on Windows, that throws

ZoneInfoNotFoundError:'未使用本地时间键找到时区'

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)

由于 time.tzname [time.daylight] 返回一个本地化名称(在我的情况下为德国语,例如MitteleuropäischeSommerzeit"),所以这也不起作用:

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

有什么想法吗?

p.s.在Python<上尝试3.9,使用 backports (另请参见此答案):

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

推荐答案

您无需使用zoneinfo即可使用系统本地时区.调用 None (或省略)时区即可.rel ="nofollow noreferrer"> datetime.astimezone .

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.

从文档中

如果不带参数调用(或使用 tz = None ),则假定为系统本地时区.转换后的datetime实例的 .tzinfo 属性将设置为具有从操作系统获得的区域名称和偏移量的时区实例.

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.

因此:

from datetime import datetime

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

这篇关于在Windows上获取本地时区名称(Python 3.9 zoneinfo)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆