【发布时间】:2017-09-16 22:58:19
【问题描述】:
我试图将一个天真的 datetime 对象与一个时区感知 datetime 对象进行比较。
我必须改变。
最初我收到此错误:
lastDate = start_date + ' ' + errorTime
lastDate = datetime.strptime(lastDate, '%Y-%m-%d %H:%M:%S')
time_diff = lastDate - FirstDate
TypeError: can't compare offset-naive and offset-aware datetimes
首先...我检查了我的两个日期时间对象的 tzinfo..
>>>FirstDate.tzinfo
>>>tzfile(u'/usr/share/zoneinfo/Europe/London')
>>>lastDate.tzinfo
>>>
这是意料之中的,因为 lastDate 不知道。
然后我导入了pytz 并转换了幼稚的lastDate 日期时间对象:
lastDate = start_date + ' ' + errorTime
lastDate = datetime.strptime(lastDate, '%Y-%m-%d %H:%M:%S')
lastDate = pytz.timezone('Europe/London').localize(lastDate)
time_diff = lastDate - FirstDate
TypeError: Timestamp subtraction must have the same timezones or no timezones
我再次检查时区:
>>>FirstDate.tzinfo
>>>tzfile(u'/usr/share/zoneinfo/Europe/London')
>>>lastDate.tzinfo
>>><DstTzInfo 'Europe/London' GMT0:00:00 STD>
我被难住了...如何给幼稚的日期时间对象lastDate 一个 tzfile?
注意:我必须转换幼稚的 datetime 对象 lastDate 以匹配 tz 感知 datetime 对象 FirstDate。我无法修改 FirstDate 的 tz。
【问题讨论】:
标签: python python-2.7 datetime timezone