Comparing a time in UTC with a time in Eastern time using Python(使用 Python 比较 UTC 时间和东部时间的时间)
问题描述
我正在尝试使用 Python datetime
模块比较两次,但我似乎无法在 UTC 中创建时区感知 time
对象.
I'm trying to compare two times using the Python datetime
module, but I can't seem to create a timezone-aware time
object in UTC.
>>> import pytz, datetime
>>> UTC_TZ = pytz.utc
>>> EASTERN_TZ = pytz.timezone('America/New_York')
>>> d1 = datetime.time(10, tzinfo = UTC_TZ)
>>> d1
datetime.time(10, 0, tzinfo=<UTC>)
>>> d2 = datetime.time(10, tzinfo = EASTERN_TZ)
>>> d2
datetime.time(10, 0, tzinfo=<DstTzInfo 'America/New_York' EST-1 day, 19:00:00 STD>)
>>> d1 < d2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can't compare offset-naive and offset-aware times
这是一个错误吗?我需要使用特殊的 UTC 时区吗?怎么回事?
Is this a bug? Is there a special UTC timezone I need to use? What's going on?
推荐答案
感谢 wberry 解决这个问题,但为了得到一个简洁的答案,我将在这里总结一下.
All credit to wberry for puzzling this out, but in the interest of having a concise answer, I'll summarize it here.
根据 datetime 文档,在比较两个 datetime.time 对象时:如果两个比较对象都知道并且具有不同的 tzinfo 属性,则首先通过减去它们的 UTC 偏移量来调整比较对象(从 self.utcoffset() 获得)"
According to the datetime docs, when comparing two datetime.time objects: "If both comparands are aware and have different tzinfo attributes, the comparands are first adjusted by subtracting their UTC offsets (obtained from self.utcoffset())"
在您给出的示例中,比较会引发 TypeError,因为 EASTERN_TZ.utcoffset() 返回 None.utcoffset 为 None 因为美国东部遵守夏令时,因此与 UTC 的时间偏移取决于 datetime.time 中不可用的日期.
In the example you gave, the comparison throws the TypeError because EASTERN_TZ.utcoffset() returns None. utcoffset is None because the eastern US observes Daylight Savings Time and so the time offset from UTC depends on the date which isn't available in datetime.time.
您应该使用 datetime.datetime 对象进行跨时区比较:
You should use datetime.datetime objects for cross-timezone comparisons:
>>> import pytz, datetime
>>> UTC_TZ = pytz.utc
>>> EASTERN_TZ = pytz.timezone('America/New_York')
>>> d1 = datetime.datetime(2012, 1, 1, 10, 0, tzinfo=UTC_TZ)
>>> d2 = datetime.datetime(2012, 1, 1, 10, 0, tzinfo=EASTERN_TZ)
>>> d1 < d2
True
这篇关于使用 Python 比较 UTC 时间和东部时间的时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 Python 比较 UTC 时间和东部时间的时间
基础教程推荐
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 筛选NumPy数组 2022-01-01