本文介绍了.localize和tzinfo之间的Python日期时间差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这两行为什么产生不同的结果?

Why do these two lines produce different results?

>>> import pytz
>>> from datetime ipmort datetime

>>> local_tz = pytz.timezone("America/Los_Angeles")

>>> d1 = local_tz.localize(datetime(2015, 8, 1, 0, 0, 0, 0)) # line 1
>>> d2 = datetime(2015, 8, 1, 0, 0, 0, 0, local_tz) # line 2
>>> d1 == d2
False

产生差异的原因是什么,应该使用哪个本地化日期时间?

What's the reason for the difference, and which should I use to localize a datetime?

推荐答案

创建 d2 = datetime(2015,8,1,0 ,0、0、0,local_tz)。它不能正确处理夏时制时间。但是, local_tz.localize()确实可以。

When you create d2=datetime(2015, 8, 1, 0, 0, 0, 0, local_tz) in this way. It does not handle daylight savings time correctly. But, local_tz.localize() does.

d1是

datetime.datetime(2015, 8, 1, 0, 0, 
                  tzinfo=<DstTzInfo 'America/Los_Angeles' PDT-1 day, 17:00:00 DST>)

d2是

datetime.datetime(2015, 8, 1, 0, 0, 
                  tzinfo=<DstTzInfo 'America/Los_Angeles' PST-1 day, 16:00:00 STD>)

您可以看到它们并不代表同一时间。

You can see that they are not representing the same time.

d2 的方式,如果您要使用UTC,那就很好。因为UTC没有夏令时转换。

d2 way it's fine if you are gonna work with UTC. Because UTC does not have daylight savings time transitions to deal with.

因此,处理时区的正确方法是使用 local_tz.localize()

So, the correct way to handle timezone, it's using local_tz.localize()

这篇关于.localize和tzinfo之间的Python日期时间差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-19 02:52