Moh*_*nan 5 python pytz python-datetime
所以我有 -
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)
Run Code Online (Sandbox Code Playgroud)
现在我想知道为什么 isoformat 添加了 05:53 的偏移量,而亚洲/加尔各答时区是 +05:30。参考 - https://www.zeitverschiebung.net/en/timezone/asia--kolkata
创建日期时间时,为 tzinfo 添加 pytz 实例几乎总是错误的。使用 pytz 将原始日期时间转换为时区感知实例的正确方法是使用区域的 localize 方法:
zone.localize(dt)
Run Code Online (Sandbox Code Playgroud)
您的案例的输出:
>>> print(timezone.localize(zoned_time_stamp))
2017-06-01 05:30:00+05:30
Run Code Online (Sandbox Code Playgroud)
有非常清楚的记录表明,在 tzinfo 中传递 pytz 实例不是创建本地化日期时间的受支持的方式。然而,这也是 Python 代码中常见的错误 - 我猜很多用户都没有阅读文档!
要了解为什么错误的方法会显示出它的作用(奇怪的+05:53偏移),请参阅Paul Ganssle 的pytz:西方最快的步枪。
| 归档时间: |
|
| 查看次数: |
226 次 |
| 最近记录: |