在 Python 中获取本地时区作为字母代码?



我通常使用以下代码来获取本地时区:

import platform
import time
import datetime
import pytz
#LOCAL_TIMEZONE = datetime.datetime.now(datetime.timezone.utc).astimezone().tzinfo # "CEST", etc on Linux, but 'Romance Standard Time' on Windows
if "win" in platform.system().lower(): # SO:1387222
# SO:16156597 - try tzlocal.win32; MINGW64: `pip3.8.exe install tzlocal`; RPi: `sudo apt install python3-tzlocal`
from tzlocal.win32 import get_localzone_name
LOCAL_TIMEZONE = pytz.timezone(get_localzone_name())
else:
from tzlocal import get_localzone
LOCAL_TIMEZONE = get_localzone()
# Above results with LOCAL_TIMEZONE: Europe/Copenhagen in Linux, Europe/Paris in Windows

如何获取适用于 Windows 和 Linux 的本地时区 CET 或 CEST(字母代码(?

tzlocal包应该能提供你需要的东西 - 但是你还需要一个datetime对象,你可以用于strftime('%Z')

from datetime import datetime
from tzlocal import get_localzone
print(datetime.now(tz=get_localzone()).strftime('%Z'))
# CEST

附言我在窗户上;现在无法在 Linux 上测试。

最新更新