首页 文章

如何将时区格式文件传递给Python中的天真日期时间对象

提问于
浏览
2

我试图比较一个天真的 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 datetime对象:

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 .

1 回答

  • 0

    您应该能够从现有的 datetime 获取时区并应用于另一个 . 尝试:

    lastDate = FirstDate.tzinfo.localize(lastDate)
    

    代替:

    lastDate = pytz.timezone('Europe/London').localize(lastDate)
    

    应该做你想做的事 .

相关问题