pytz localize vs datetime replace(pytz 本地化与日期时间替换)
问题描述
我在使用 pytz 的 .localize() 函数时遇到了一些奇怪的问题.有时它不会对本地化的日期时间进行调整:
I'm having some weird issues with pytz's .localize() function. Sometimes it wouldn't make adjustments to the localized datetime:
.localize 行为:
.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>)
如您所见,本地化/规范化操作并未改变时间.但是,如果使用 .replace:
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?
推荐答案
localize
只是假设您传递给它的天真日期时间是正确的"(除了不知道时区!)等等只是设置时区,没有其他调整.
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.
您可以(并且建议...)在 UTC 内部工作(而不是使用简单的日期时间)并在需要以本地化方式执行日期时间的 I/O 时使用 replace
(normalize
将处理 DST 等).
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 本地化与日期时间替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:pytz 本地化与日期时间替换


基础教程推荐
- 用于分类数据的跳跃记号标签 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 筛选NumPy数组 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01