使用 Python 比较 UTC 时间和东部时间的时间

Comparing a time in UTC with a time in Eastern time using Python(使用 Python 比较 UTC 时间和东部时间的时间)

本文介绍了使用 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 时间和东部时间的时间

基础教程推荐