我的时区格式如下:“RTZ 2 (зима)”
如您所见,这是西里尔字母。我需要将其应用于时间戳。
我知道
pytz
模块可以从时区名称创建 tz
子类。然而当我这样做时:
try:
t = datetime.fromtimestamp(timestamp).astimezone(pytz.timezone("RTZ 2 (зима)"))
except Exception as e:
print("Exception: " + str(e))
我得到这个例外:
Exception: 'RTZ 2 (зима)\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
如何将此格式“RTZ 2 (зима)”转换为
pytz
识别的正确时区?我应该使用另一个可以理解这个名称的模块吗?
感谢您的帮助。
在 Python 的 pytz 库中,时区通常使用“Europe/Moscow”等字符串表示,而不是“RTZ 2 (зима)”。
import pytz
from datetime import datetime
timestamp = 1628685962 # Replace with your timestamp
tz = pytz.timezone("Europe/Moscow") # Use the correct timezone string
t = datetime.fromtimestamp(timestamp).astimezone(tz)
print(t)
问题看起来像是编码。如果将字符串编码为 utf-8 并再次解码,则可以确保正确处理西里尔字符。
tz_name = "RTZ 2 (зима)".encode("utf-8")
decoded_tz_name = tz_name.decode("utf-8")
timestamp = 1631366400
t = datetime.fromtimestamp(timestamp, tz=pytz.timezone(decoded_tz_name))