将UTC中的时间与东部时间的Python进行比较 [英] Comparing a time in UTC with a time in Eastern time using Python

查看:295
本文介绍了将UTC中的时间与东部时间的Python进行比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Python datetime 模块进行两次比较,但我似乎无法创建时区感知 / code>对象在UTC。

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

这是一个bug?有没有特殊的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

这篇关于将UTC中的时间与东部时间的Python进行比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆