我有一个程序,指定什么时候警报应该是活动的(例如,上午10点到晚上8点)。我的程序的一部分,然后检查警报是否现在是有效的。“it it active”检查器需要处理跨越午夜边界到明天(例如,晚上8点到上午10点警报)的警报范围。
我目前正在使用相同的冗余函数来处理这个问题,除了进行和vs或比较之外。请问有什么更好的方法?(当然,任何其他评论也是最受欢迎的。)
import datetime as dt
def check_alarm_bounds_on_same_date(time_now, time_of_day_bounds):
time_start_of_current_day = dt.datetime.combine(time_now.date(), dt.datetime.min.time())
if ( time_now >= (time_start_of_current_day + dt.timedelta(hours=time_of_day_bounds[0])) and #<< AND
time_now < (time_start_of_current_day + dt.timedelta(hours=time_of_day_bounds[1])) ):
return True
return False
def check_alarm_bounds_on_different_dates(time_now, time_of_day_bounds):
time_start_of_current_day = dt.datetime.combine(time_now.date(), dt.datetime.min.time())
if ( time_now >= (time_start_of_current_day + dt.timedelta(hours=time_of_day_bounds[0])) or #<< OR
time_now < (time_start_of_current_day + dt.timedelta(hours=time_of_day_bounds[1])) ):
return True
return False
def is_alarm_live(time_current, time_of_day_bounds):
alarm_start_time = time_of_day_bounds[0]
alarm_end_time = time_of_day_bounds[1]
if alarm_end_time <= alarm_start_time:
return check_alarm_bounds_on_different_dates(time_current, time_of_day_bounds)
else:
return check_alarm_bounds_on_same_date(time_current, time_of_day_bounds)
# specify two alarm periods (#1 @ 10AM-8PM; #2 @ 8PM-10AM next day)
alarms = [(10,20),(20,10)]
for hour in range(0,24):
# test all hours in a sample day, and output which alarm is active
print 'hour %i: ' % hour,
time_test = dt.datetime(2017,01,22,hour,10,30)
for alarm in alarms:
print is_alarm_live(time_test, alarm),
print ''发布于 2017-01-22 21:03:19
非常快速的复习。
datetime.datetime.combine使datetime.datetime对象表示边界,然后将这些对象与time_current进行比较。但是,让datetime.time对象表示边界,然后将这些对象与time_current.time进行比较会更简单。datetime.time对象作为其第一个参数,则会更简单,如果需要的话,则由调用方传递time_current.time。经修订的守则:
import datetime
def time_in_range(time, start_hour, end_hour):
"""Return True if time (a datetime.time object) lies between
start_hour and end_hour (inclusive).
>>> time_in_range(datetime.time(hour=12), 10, 14)
True
The range is allowed to span midnight:
>>> time_in_range(datetime.time(hour=0), 22, 2)
True
"""
start = datetime.time(hour=start_hour)
end = datetime.time(hour=end_hour)
if end <= start: # Range spans midnight.
return start <= time or time <= end
else:
return start <= time <= endhttps://codereview.stackexchange.com/questions/153304
复制相似问题