我正在尝试找到最干净/最Pythonic的方法来评估“现在”是否在两个时间之间;但是,开始/结束时间可能跨越一天边界,也可能不跨越-例如(只是使用简单的例子):
onhour=23
onmin=30
offhour=4
offmin=15
timenow = datetime.datetime.now().time()
对于这个问题,简单的 if START < NOW < END
场景不适用!
我目前拥有一些代码,用于判断当前是否为“夜间”,它看起来像这样:
def check_time(timenow, onhour, onmin, offhour, offmin, verbose):
now = datetime.datetime.now()
now_time = now.time()
# If we're actually scheduling at night:
if int(offhour) < int(onhour):
# Check to see if we're in daylight times (ie. off schedule)
if datetime.time(int(offhour),int(offmin)) <= now_time <= datetime.time(int(onhour),int(onmin)):
if verbose == True:
print("Day Time detected.")
return False
else:
if verbose == True:
print("Night Time detected.")
return True
else:
if datetime.time(int(onhour),int(onmin)) <= now_time <= datetime.time(int(offhour),int(offmin)):
if verbose == True:
print("Night Time detected.")
return True
else:
if verbose == True:
print("Day Time detected.")
return False
如果标题看起来不像是什么新鲜事,我表示歉意,但是在回顾了一些类似问题的现有答案后,例如:
我注意到这些答案似乎没有考虑开始和结束时间跨越一天边界的情况。
除此之外,任何关于基于日期的计划的想法也会非常有用!例如,“从周一到周五,在23:00打开,在04:00关闭”——但要管理前后两天的开关(否则,某些设备可能在周五打开,但在周六未关闭,然后包括周六意味着它又会在23:00重新打开!...)
我考虑过简单地“在X点打开,睡眠Y秒”来解决这个问题...但如果脚本在“开启”周期内启动,则要等到下一次运行才会启动... 但这似乎是最简单的选择! :)
我希望有一些很棒的模块可以完成所有这些... :D
对我来说,Python2.7-3.2的兼容性也非常重要!
date1 <= date2 <= date3
就可以正常工作。 - Simeon Visseroffhour
应该分配给今天还是明天...我猜测评估time.now()
是否大于offhour
或类似的方法可能已经足够了... - dalgibbard