python中的datetime模块的isoformat函数返回错误的偏移量

问题描述

我有-

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会添加一个05:53的偏移量,而亚洲/加尔各答的时区为+05:30。 ref-https://www.zeitverschiebung.net/en/timezone/asia--kolkata

解决方法

在创建日期时间时,仅仅为tzinfo添加一个pytz实例几乎总是错误的。使用pytz将天真日期时间转换为可识别时区的实例的正确方法是使用该区域的localize方法:

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