I typically use this code to obtain local timezone:
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
How can I obtain the local timezone as CET or CEST (letter code) that works in both Windows and Linux?
解决方案
the tzlocal package should provide you with what you need - however you also need a datetime object that you can use for strftime('%Z'):
from datetime import datetime
from tzlocal import get_localzone
print(datetime.now(tz=get_localzone()).strftime('%Z'))
# CEST
p.s. I'm on Windows; can't test right now on Linux.