pytz:为什么在时区之间转换时需要归一化? [英] pytz: Why is normalize needed when converting between timezones?

查看:33
本文介绍了pytz:为什么在时区之间转换时需要归一化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读不那么完整的 pytz 文档,但我一直在理解其中的一部分.

<块引用>

时区之间的转换也需要特别注意.这也需要使用normalize方法来保证转换正确.

<预><代码>>>>utc_dt = utc.localize(datetime.utcfromtimestamp(1143408899))>>>utc_dt.strftime(fmt)'2006-03-26 21:34:59 UTC+0000'>>>au_tz = timezone('澳大利亚/悉尼')>>>au_dt = au_tz.normalize(utc_dt.astimezone(au_tz))>>>au_dt.strftime(fmt)'2006-03-27 08:34:59 EST+1100'>>>utc_dt2 = utc.normalize(au_dt.astimezone(utc))>>>utc_dt2.strftime(fmt)'2006-03-26 21:34:59 UTC+0000'

我使用normalize 尝试了这个没有的例子,结果是一样的.在我看来,这个例子并没有真正解释为什么在不同时区的 datetime 对象之间转换时我们必须使用 normalize.

有人请给我一个示例(如上面的示例),其中不使用 normalize 时的结果不同.

谢谢

解决方案

来自 pytz 文档:

<块引用>

此外,如果您对跨越 DST 边界的本地时间执行日期算术,则结果可能位于不正确的时区(即从 2002-10-27 1:00 EST 减去 1 分钟,您会得到 2002-10-27 0:59 EST 而不是正确的 2002-10-27 1:59 EDT).提供了一个 normalize() 方法来纠正这个问题.不幸的是,如果不修改 Python 日期时间实现,这些问题就无法解决.

I'm reading the not so complete pytz documentation and I'm stuck on understand one part of it.

Converting between timezones also needs special attention. This also needs to use the normalize method to ensure the conversion is correct.

>>> utc_dt = utc.localize(datetime.utcfromtimestamp(1143408899))
>>> utc_dt.strftime(fmt)
'2006-03-26 21:34:59 UTC+0000'
>>> au_tz = timezone('Australia/Sydney')
>>> au_dt = au_tz.normalize(utc_dt.astimezone(au_tz))
>>> au_dt.strftime(fmt)
'2006-03-27 08:34:59 EST+1100'
>>> utc_dt2 = utc.normalize(au_dt.astimezone(utc))
>>> utc_dt2.strftime(fmt)
'2006-03-26 21:34:59 UTC+0000'

I tried this very example without using normalize and it turned out just the same. In my opinion this example doesn't really explain why we have to use normalize when converting between datetime objects in different timezones.

Would someone please give me an example (like the one above) where the result differs when not using normalize.

Thanks

解决方案

From the pytz documentation:

In addition, if you perform date arithmetic on local times that cross DST boundaries, the results may be in an incorrect timezone (ie. subtract 1 minute from 2002-10-27 1:00 EST and you get 2002-10-27 0:59 EST instead of the correct 2002-10-27 1:59 EDT). A normalize() method is provided to correct this. Unfortunately these issues cannot be resolved without modifying the Python datetime implementation.

这篇关于pytz:为什么在时区之间转换时需要归一化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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