【问题标题】:Get local timezone as letter code in Python?在 Python 中获取本地时区作为字母代码?
【发布时间】:2020-07-02 14:54:44
【问题描述】:

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

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(字母代码)?

【问题讨论】:

标签: python datetime


【解决方案1】:

tzlocal 包应该为您提供所需的东西 - 但是您还需要一个可用于 strftime('%Z')datetime 对象:

from datetime import datetime
from tzlocal import get_localzone

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

附言我在 Windows 上;目前无法在 Linux 上进行测试。

【讨论】:

  • 完美,谢谢 - 适用于 Windows 和 Raspberry Pi Raspbian
猜你喜欢
  • 1970-01-01
  • 2016-05-05
  • 1970-01-01
  • 2018-11-03
  • 2013-01-17
  • 1970-01-01
  • 2011-06-02
  • 2013-07-17
  • 2015-05-26
相关资源
最近更新 更多