提问者:小点点

在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或CET(字母代码)的本地时区?


共1个答案

匿名用户

TZLocal包应该为您提供所需的内容-但是,您还需要一个DateTime对象,可以用于StrfTime('%z'):

from datetime import datetime
from tzlocal import get_localzone

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

附注。 我在Windows上; 现在无法在Linux上测试。