如何在 Python 中打印出时间对象的时区?

How to print out the timezone for a time object in Python?

我正在尝试以 '%H:%M:%S%z' 格式将时区信息作为字符串打印出来。为此,我正在执行以下操作:

import pytz
import datetime

tz = pytz.timezone('Africa/Cairo')
time = datetime.datetime.strptime('14:24:41', '%H:%M:%S').time()
time = time.replace(tzinfo=tz)

print(time.strftime('%H:%M:%S%z'))

我得到的结果只是 '14:24:41',即使在替换了 tzinfo 之后也是如此。我在这里做错了什么?

编辑 这个问题不是重复的,因为另一个问题没有解释为什么不使用 strftime() 方法打印时区。

来自 datetime 包,%z

UTC offset in the form ±HHMM[SS[.ffffff]] (empty string if the object is naive).

For a naive object, the %z and %Z format codes are replaced by empty strings. For an aware object:

%z

utcoffset() is transformed into a string of the form ±HHMM[SS[.ffffff]], where HH is a 2-digit string giving the number of UTC offset hours, MM is a 2-digit string giving the number of UTC offset minutes, SS is a 2-digit string giving the number of UTC offset seconds and ffffff is a 6-digit string giving the number of UTC offset microseconds.

使用您的示例代码,time.utcoffset() returns 为空。

编辑,修复

您可能想使用 .localize() 方法,但为此您需要将字符串转换为 datetime.datetime 而不是 datetime.time 对象。这在某种程度上是有道理的:东京星期三 0100,柏林 星期二 1700。

import pytz
import datetime

tz = pytz.timezone('Africa/Cairo')
dt = datetime.datetime.strptime('14:24:41', '%H:%M:%S')
time = tz.localize(dt)

print(time.strftime('%H:%M:%S%z'))