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

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

问题描述

我尝试使用datetime和pytz在python中创建一个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

显示的输出是

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

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

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?

推荐答案

href =http://bytes.com/topic/python/answers/676275-pytz-giving-incorrect-offset-timezone =noreferrer> http://bytes.com/topic/python/answers/676275 -pytz-give-incorrect-offset-timezone

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

在评论中,有人建议使用 tzinfo.localize()而不是 datetime 构造函数,这是一个诀窍。

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>)

更新:其实,官方pytz网站表示,您应该始终使用 localize astimezone 而不是传递时区对象到 datetime.datetime

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天全站免登陆