获取本地时区作为Python中的字母代码? [英] Get local timezone as letter code in Python?
本文介绍了获取本地时区作为Python中的字母代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我通常使用以下代码获取本地时区:
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
如何获取在Windows和Linux上均可使用的本地时区作为CET或CEST(字母代码)?
How can I obtain the local timezone as CET or CEST (letter code) that works in both Windows and Linux?
推荐答案
tzlocal
包应为您提供什么您需要-但是您还需要一个 datetime
对象,该对象可用于 strftime('%Z')
:
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
ps我在Windows上;目前无法在Linux上进行测试。
p.s. I'm on Windows; can't test right now on Linux.
这篇关于获取本地时区作为Python中的字母代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文