python returns 中日期时间模块的等格式函数不正确的偏移量

isoformat function of datetime module in python returns incorrect offset

所以我有 -

timezone = pytz.timezone('Asia/Kolkata')
one_time_stamp = '2017-06-01 05:30:00'

zoned_time_stamp = datetime.datetime.strptime(one_time_stamp, '%Y-%m-%d %H:%M:%S')

#This outputs 2017-06-01 05:30:00 which is fine.
print(zoned_time_stamp)

#notice timezone added
non_iso_zoned_ts = zoned_time_stamp.replace(microsecond=0, tzinfo=timezone)
# This outputs 2017-06-01 05:30:00 which is fine.
print(zoned_time_stamp)

iso_date = non_iso_zoned_ts.isoformat()
#This outputs 2017-06-01T05:30:00+05:53 which is incorrect. Ideally it should be 2017-06-01T05:30:00+05:30
print(iso_date)

现在我想知道为什么 isoformat 在时区 Asia/Kolkata 是 +05:30 时添加偏移量 05:53。参考 - https://www.zeitverschiebung.net/en/timezone/asia--kolkata

在创建日期时间时只为 tzinfo 添加一个 pytz 实例几乎总是错误的。使用 pytz 将原始日期时间转换为时区感知实例的正确方法是使用区域的本地化方法:

zone.localize(dt)

您案例的输出:

>>> print(timezone.localize(zoned_time_stamp))
2017-06-01 05:30:00+05:30

相当 clearly documented 在 tzinfo 中传递 pytz 实例不是创建本地化日期时间的受支持方式。然而,这也是 Python 代码中常见的错误 - 我猜很多用户没有阅读文档!

要了解为什么不正确的方法显示了它所做的(奇怪的 +05:53 偏移),请参阅 Paul Ganssle 的 pytz: The Fastest Footgun in the West