datetime and timezone conversion with pytz - mind blowing behaviour(使用 pytz 进行日期时间和时区转换 - 令人兴奋的行为)
问题描述
我正在尝试将时区感知 datetime 对象转换为 UTC,然后再转换回原来的时区.我有以下片段
I'm trying to convert timezone aware datetime object to UTC and then back to it's original timezone. I have a following snippet
t = datetime(
2013, 11, 22, hour=11, minute=0,
tzinfo=pytz.timezone('Europe/Warsaw')
)
现在在 ipython 中:
now in ipython:
In [18]: t
Out[18]: datetime.datetime(
2013, 11, 22, 11, 0, tzinfo=<DstTzInfo 'Europe/Warsaw' WMT+1:24:00 STD>
)
现在让我们尝试转换为 UTC 并返回.我希望具有与以下相同的表示:
and now let's try to do conversion to UTC and back. I would expect to have the same representation as:
In [19]: t.astimezone(pytz.utc).astimezone(pytz.timezone('Europe/Warsaw'))
Out[19]: datetime.datetime(
2013, 11, 22, 10, 36, tzinfo=<DstTzInfo 'Europe/Warsaw' CET+1:00:00 STD>
)
然而我们看到 Out[18] 和 Out[19] 不同.怎么回事?
Yet we see that Out[18] and Out[19] differ. What's going on?
推荐答案
文档 http://pytz.sourceforge.net/ 声明不幸的是,对于许多时区,使用标准日期时间构造函数的 tzinfo 参数对 pytz '不起作用'."代码:
The documentation http://pytz.sourceforge.net/ states "Unfortunately using the tzinfo argument of the standard datetime constructors 'does not work' with pytz for many timezones." The code:
t = datetime(
2013, 5, 11, hour=11, minute=0,
tzinfo=pytz.timezone('Europe/Warsaw')
)
按照这个不行,你应该使用localize方法:
doesn't work according to this, instead you should use the localize method:
t = pytz.timezone('Europe/Warsaw').localize(
datetime(2013, 5, 11, hour=11, minute=0))
这篇关于使用 pytz 进行日期时间和时区转换 - 令人兴奋的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 pytz 进行日期时间和时区转换 - 令人兴奋的行为
基础教程推荐
- Kivy 使用 opencv.调整图像大小 2022-01-01
- Python 中是否有任何支持将长字符串转储为块文字或折叠块的 yaml 库? 2022-01-01
- Python,确定字符串是否应转换为 Int 或 Float 2022-01-01
- kivy 应用程序中的一个简单网页作为小部件 2022-01-01
- 究竟什么是“容器"?在蟒蛇?(以及所有的 python 容器类型是什么?) 2022-01-01
- 比较两个文本文件以找出差异并将它们输出到新的文本文件 2022-01-01
- 在 Django Admin 中使用内联 OneToOneField 2022-01-01
- matplotlib 设置 yaxis 标签大小 2022-01-01
- 在 Python 中将货币解析为数字 2022-01-01
- 对多索引数据帧的列进行排序 2022-01-01
