在python中转换时区的意外结果 [英] unexpected results converting timezones in python

查看:47
本文介绍了在python中转换时区的意外结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图理解为什么在将时区转换为 UTC 时会得到这些结果:

I'm trying to understand why I'm getting these results when converting timezones to UTC:

In [74]: d1 = datetime(2007, 12, 5, 6, 30,tzinfo=pytz.timezone('US/Pacific'))
In [75]: d1
Out[75]: datetime.datetime(2007, 12, 5, 6, 30, tzinfo=<DstTzInfo 'US/Pacific' LMT-1 day, **16:07:00 STD**>)
In [76]: d1.astimezone(pytz.utc)
Out[76]: datetime.datetime(2007, 12, 5, 14, 23, tzinfo=<UTC>)

为什么早上 6:30 变成了下午 2:23?

Why did 6:30am become 2:23pm?

另一方面,如果我使用以下方法,我会得到预期的结果:

On the other hand, if I use the following approach, I get the expected result:

In [90]: d2 = datetime(2007, 12, 5, 6, 30)
In [91]: uspac = pytz.timezone('US/Pacific')
In [92]: d2_aware = uspac.localize(d2)
In [94]: d2_aware.astimezone(pytz.utc)
Out[94]: datetime.datetime(2007, 12, 5, 14, 30, tzinfo=<UTC>)

推荐答案

来自部分文档:http://pytz.sourceforge.net/#localized-times-and-date-arithmetic

不幸的是,对于许多时区,在 pytz 中使用标准日期时间构造函数的 tzinfo 参数不起作用".[...] 但是对于没有夏令时转换的时区是安全的,例如 UTC.[...] 处理时间的首选方式是始终使用 UTC,仅在生成供人类读取的输出时才转换为本地时间.

Unfortunately using the tzinfo argument of the standard datetime constructors ‘’does not work’’ with pytz for many timezones. [...] It is safe for timezones without daylight saving transitions though, such as UTC. [...] The preferred way of dealing with times is to always work in UTC, converting to localtime only when generating output to be read by humans.

这篇关于在python中转换时区的意外结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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