Python datetime 对象显示错误的时区偏移 [英] Python datetime object show wrong timezone offset

查看:42
本文介绍了Python datetime 对象显示错误的时区偏移的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试在 python 中使用 datetime 和 pytz 创建一个 datetime 对象,显示的偏移量是错误的.

导入日期时间从 pytz 导入时区start = datetime.datetime(2011, 6, 20, 0, 0, 0, 0, timezone('Asia/Kolkata'))打印开始

显示的输出是

datetime.datetime(2011, 6, 20, 0, 0, tzinfo=<DstTzInfo 'Asia/Kolkata' HMT+5:53:00 STD>)

请注意,亚洲/加尔各答"是 IST,即 GMT+5:30 而不是 HMT+5:53.这是一个标准的linux时区,为什么我会出错,我该如何解决?

解决方案

参见:http://bytes.com/topic/python/answers/676275-pytz-giving-incorrect-offset-timezone

在评论中,有人建议使用 tzinfo.localize() 而不是 datetime 构造函数,它可以做到这一点.

<预><代码>>>>tz = timezone('亚洲/加尔各答')>>>dt = tz.localize(datetime.datetime(2011, 6, 20, 0, 0, 0, 0))>>>dtdatetime.datetime(2011, 6, 20, 0, 0, tzinfo=<DstTzInfo 'Asia/Kolkata' IST+5:30:00 STD>)

更新:实际上,官方 pytz 网站 指出您应该始终使用localizeastimezone 而不是将时区对象传递给 datetime.datetime.

I am try creating a datetime object in python using datetime and pytz, the offset shown is wrong.

import datetime
from pytz import timezone

start = datetime.datetime(2011, 6, 20, 0, 0, 0, 0, timezone('Asia/Kolkata'))
print start

The output shown is

datetime.datetime(2011, 6, 20, 0, 0, tzinfo=<DstTzInfo 'Asia/Kolkata' HMT+5:53:00 STD>)

Note that 'Asia/Kolkata' is IST which is GMT+5:30 and not HMT+5:53. This is a standard linux timezone, why do I get this wrong, and how do I solve it?

解决方案

See: http://bytes.com/topic/python/answers/676275-pytz-giving-incorrect-offset-timezone

In the comments, someone proposes to use tzinfo.localize() instead of the datetime constructor, which does the trick.

>>> tz = timezone('Asia/Kolkata')
>>> dt = tz.localize(datetime.datetime(2011, 6, 20, 0, 0, 0, 0))
>>> dt
datetime.datetime(2011, 6, 20, 0, 0, tzinfo=<DstTzInfo 'Asia/Kolkata' IST+5:30:00 STD>)

UPDATE: Actually, the official pytz website states that you should always use localize or astimezone instead of passing a timezone object to datetime.datetime.

这篇关于Python datetime 对象显示错误的时区偏移的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆