简体   繁体   English

通过考虑时区比较时间

[英]Comparing times by considering time zones

According to Convert UTC to local time to UTC in Python and Google App Engine , to correctly compare the times of now and a target time (considering different time zones), I have to convert the target time to UTC as follows: 根据Python和Google App Engine中的将UTC转换为本地时间到UTC ,要正确比较现在时间和目标时间(考虑不同时区),我必须将目标时间转换为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():
    ...

Questions: 问题:

  1. Is this correct? 这个对吗?
  2. There is an error message: 没有错误消息:

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

    How to solve it? 怎么解决呢?

its because one of your datetime objects has a timezone set and the other one doesn't. 这是因为您的一个datetime对象设置了时区,而另一个没有。
take a look here and here 看看这里这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM