怎样才能最好地判断当前时间是否在 10:30 AM
和 4:30 PM
之间呢?
我能想到以下方法,但不确定是否正确:
from datetime import datetime
nw = datetime.now()
hrs = nw.hour;mins = nw.minute;secs = nw.second;
zero = timedelta(seconds = secs+mins*60+hrs*3600)
st = nw - zero # this take me to 0 hours.
time1 = st + timedelta(seconds=10*3600+30*60) # this gives 10:30 AM
time2 = st + timedelta(seconds=16*3600+30*60) # this gives 4:30 PM
if nw>= time1 or nw <= time2:
print "yes, within the interval"
请告诉我这是否是正确的方法,是否有更好的写法?
timedelta()
允许您指定天数、小时和分钟,因此您不必进行计算,代码更易读。 - C2H5OH