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 时间和东部时间的时间
基础教程推荐
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
