【问题标题】:How to pass a timezone format file to a naive datetime object in Python如何将时区格式文件传递给 Python 中的天真日期时间对象
【发布时间】: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


    【解决方案1】:

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

    lastDate = FirstDate.tzinfo.localize(lastDate)
    

    代替:

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

    那应该做你所追求的。

    【讨论】:

    • 嗨@Stephen 我试过这个,现在我收到以下错误:AttributeError: 'tzfile' object has no attribute 'localize'
    【解决方案2】:

    我是这样设计的:

    lastDate = lastDate.replace(tzinfo=FirstDate.tzinfo)
    lastDate - FirstDate
    

    仅替换原始日期时间上的 tzinfo 属性

    【讨论】:

      猜你喜欢
      • 2012-05-05
      • 2022-09-24
      • 2020-10-25
      • 2018-12-06
      • 2018-07-29
      • 2019-04-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多