datetime
对象有一个调用的方法time()
,它返回一个time
对象(没有日期信息)。然后,您可以time
使用法线<
或>
运算符比较对象。
import datetime
import time
timestamp = datetime.datetime.now().time() # Throw away the date information
time.sleep(1)
print (datetime.datetime.now().time() > timestamp) # >>> True (unless you ran this one second before midnight!)
# Or check if a time is between two other times
start = datetime.time(8, 30)
end = datetime.time(15)
print (start <= timestamp <= end) # >>> depends on what time it is
如果您还想检查工作日,您建议的代码可能是最有效的方法,但在这种情况下,您可能不想丢弃原始datetime
对象。
now = datetime.datetime.now()
if 0 <= now.weekday() <= 4:
print ("It's a weekday!")
print (start <= now.time() <= end) # with start & end defined as above