gpt4 book ai didi

python - python中datetime模块的isoformat函数返回不正确的偏移量

转载 作者:行者123 更新时间:2023-12-04 15:16:30 24 4
gpt4 key购买 nike

所以我有 -

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。引用 - 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 偏移量),请参阅 pytz: The Fastest Footgun in the West保罗·甘斯勒。

关于python - python中datetime模块的isoformat函数返回不正确的偏移量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64237253/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com