【发布时间】:2020-11-07 14:24:27
【问题描述】:
我有这个功能可以检查一周中的特定时间和日期。 它应该从周日晚上 7:00 到周五晚上 8:00 打印 1 并从周五晚上 8:00 到周日晚上 7:00 打印 0
我在星期五上午 11:00 和下午 2:00 左右检查了该函数,我在标题中收到错误消息。
有人可以准确解释错误的含义吗?我怎么可能修复它?它应该总是检查东部标准时间的时间
import pytz
from datetime import datetime, time, date
est = pytz.timezone('EST')
Mon = 0
Tue = 1
Wed = 2
Thur = 3
Fri = 4
Sat = 5
Sun = 6
weekdays = [Mon, Tue, Wed, Thur]
edgecases = [Sun, Fri]
weekend = [Sat]
curr_day = datetime.now(tz=est).date().weekday()
curr_time = datetime.now(tz=est).time()
def checktime(curr_day, curr_time):
if curr_day in weekdays or (curr_day == Sun and curr_time > time(19,00,tzinfo=est)) or (curr_day == Fri and curr_time < time(20,00,tzinfo=est)):
print(1)
elif curr_day in weekend or (curr_day == Fri and curr_time >= time(20,00,tzinfo=est)) or (curr_day == Sun and curr_time <= time(19,00,tzinfo=est)):
print(0)
回溯错误:
Traceback (most recent call last):
File ".\testingtime.py", line 73, in <module>
checktime(curr_day, curr_time)
File ".\testingtime.py", line 67, in checktime
if curr_day in weekdays or (curr_day == Sun and curr_time > time(19,00,tzinfo=est)) or (curr_day == Fri and curr_time < time(20,00,tzinfo=est)):
TypeError: can't compare offset-naive and offset-aware times
【问题讨论】:
-
您应该始终在问题中包含完整的错误跟踪,它有助于准确识别错误发生的位置。
-
是的,我现在补充一下
-
为什么首先要添加时区?如果您只比较 时间,那是没有意义的,因为时区可以有 DST 更改(例如 EST 到 EDT) - 这取决于 日期。
-
我要添加一个时区,因为我想忽略 EDT,只比较 EST 时间。如果这不可能,那么您知道我该如何改变它吗?
-
好的,我明白了 ;-) 好吧,我想既然你还是要与静态时间进行比较(
curr_time在.time()之后没有时区),你可以在比较中删除时区,例如curr_time > time(19,00)等等。
标签: python datetime time python-datetime pytz