本文介绍了pytz本地化vs datetime替换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些奇怪的问题与pytz的.localize()函数。有时它不会调整本地化的日期时间:



.localize行为:

 code>>>> tz 
< DstTzInfo'Africa / Abidjan'LMT-1 day,23:44:00 STD>
>>> d
datetime.datetime(2009,9,2,14,45,42,91421)

>>> tz.localize(d)
datetime.datetime(2009,9,2,14,45,42,91421,
tzinfo =< DstTzInfo'Africa / Abidjan'GMT0:00:00 STD>
>>> tz.normalize(tz.localize(d))
datetime.datetime(2009,9,2,14,45,42,91421,
tzinfo =< DstTzInfo'Africa / Abidjan'GMT0:00 :00 STD>)

正如你所看到的,由于本地化/规范化操作。
但是,如果使用.replace:

 >>> d.replace(tzinfo = tz)
datetime.datetime(2009,9,2,14,45,42,91421,
tzinfo =< DstTzInfo'Africa / Abidjan'LMT-1 day,23 :44:00 STD>)
>>> tz.normalize(d.replace(tzinfo = tz))
datetime.datetime(2009,9,2,15,1,42,91421,
tzinfo =< DstTzInfo'Africa / Abidjan'GMT0 :00:00 STD>)

哪个似乎调整到datetime。



问题是 - 哪个是正确的,为什么其他的错误?



谢谢!

解决方案

localize 只是假定你传递的naive datetime是对(除了不知道关于时区!),所以只是设置时区,没有其他的调整。



你可以(和它是可取的...)内部工作在UTC(而不是天真的datetimes),并且当您需要以本地化的方式执行数据时间的I / O时,使用替换 normalize 将处理DST等等)。


I'm having some weird issues with pytz's .localize() function. Sometimes it wouldn't make adjustments to the localized datetime:

.localize behaviour:

>>> tz
<DstTzInfo 'Africa/Abidjan' LMT-1 day, 23:44:00 STD>
>>> d
datetime.datetime(2009, 9, 2, 14, 45, 42, 91421)

>>> tz.localize(d)
datetime.datetime(2009, 9, 2, 14, 45, 42, 91421,
                  tzinfo=<DstTzInfo 'Africa/Abidjan' GMT0:00:00 STD>)
>>> tz.normalize(tz.localize(d))
datetime.datetime(2009, 9, 2, 14, 45, 42, 91421,
                  tzinfo=<DstTzInfo 'Africa/Abidjan' GMT0:00:00 STD>)

As you can see, time has not been changed as a result of localize/normalize operations.However, if .replace is used:

>>> d.replace(tzinfo=tz)
datetime.datetime(2009, 9, 2, 14, 45, 42, 91421,
                  tzinfo=<DstTzInfo 'Africa/Abidjan' LMT-1 day, 23:44:00 STD>)
>>> tz.normalize(d.replace(tzinfo=tz))
datetime.datetime(2009, 9, 2, 15, 1, 42, 91421,
                  tzinfo=<DstTzInfo 'Africa/Abidjan' GMT0:00:00 STD>)

Which seems to make adjustments into datetime.

Question is - which is correct and why other's wrong?

Thanks!

解决方案

localize just assumes that the naive datetime you pass it is "right" (except for not knowing about the timezone!) and so just sets the timezone, no other adjustments.

You can (and it's advisable...) internally work in UTC (rather than with naive datetimes) and use replace when you need to perform I/O of datetimes in a localized way (normalize will handle DST and the like).

这篇关于pytz本地化vs datetime替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 17:09