Python 具有偏移感知和偏移初始时间的问题

Python 具有偏移感知和偏移初始时间的问题,python,datetime,time,timezone,Python,Datetime,Time,Timezone,我使用下面的代码片段来检测特定时间是否在2个时间内(所有时间都设置为UTC时区)。但是,这段代码引发了一个异常,抱怨我正在比较偏移感知时间和偏移原始时间。我希望能对此有所了解 currentTime = datetime.datetime.now(pytz.utc).time() t1 = datetime.time(9, 0, 0, tzinfo=pytz.utc) t2 = datetime.time(11, 0, 0, tzinfo=pytz.utc) if t1 < current

我使用下面的代码片段来检测特定时间是否在2个时间内(所有时间都设置为UTC时区)。但是,这段代码引发了一个异常,抱怨我正在比较偏移感知时间和偏移原始时间。我希望能对此有所了解

currentTime = datetime.datetime.now(pytz.utc).time()
t1 = datetime.time(9, 0, 0, tzinfo=pytz.utc)
t2 = datetime.time(11, 0, 0, tzinfo=pytz.utc)
if t1 < currentTime and t2 > currentTime:
    return True
return False
currentTime=datetime.datetime.now(pytz.utc.time())
t1=datetime.time(9,0,0,tzinfo=pytz.utc)
t2=datetime.time(11,0,0,tzinfo=pytz.utc)
如果t1currentTime:
返回真值
返回错误

这里发生的事情似乎是我在转换时间时失去了时区

要纠正这一点。我必须做以下的事情

currentTime =  currentTime.replace(tzinfo=pytz.UTC)

由于与UTC的偏移量取决于时区,并且这些时间会随着年份的变化而变化,因此,没有UTC偏移量的日期的时间没有多大意义。例如,您可以在这里分别比较时间和UTC偏移量。