通过考虑时区来比较时间

时间:2012-12-22 15:08:01

标签: python google-app-engine pytz

根据Convert UTC to local time to UTC in Python and Google App Engine,为了正确比较现在的时间和目标时间(考虑不同的时区),我必须将目标时间转换为UTC,如下所示:

import pytz

def toUTC(date, tz):
    tz = pytz.timezone('Asia/Taipei')
    utc = pytz.timezone('UTC')
    d_tz = tz.normalize(tz.localize(date))
    d_utc = d_tz.astimezone(utc)
    return d_utc

days = 10
minutes = 20
targetTime = datetime.datetime(2012,12,22,0,0,0)
targetTime = targetTime + datetime.timedelta(days=days, minutes=minutes)
targetTime = toUTC(targetTime) 

if targetTime < datetime.datetime.now():
    ...

问题:

  1. 这是对的吗?
  2. 有错误消息:

    TypeError: can't compare offset-naive and offset-aware datetimes

    如何解决?

1 个答案:

答案 0 :(得分:1)

因为你的一个datetime对象设置了时区而另一个没有设置 看一看herehere