我试图找到最干净/最pythonic的方式来评估“ now”是否介于两次之间;然而; 例如,“开始/结束时间”可能会跨越一天的边界,也可能不会跨越一天的边界(仅使用简单的示例):
onhour=23 onmin=30 offhour=4 offmin=15 timenow = datetime.datetime.now().time()
做一个简单的if START < NOW < END方案是行不通的!
if START < NOW < END
我目前拥有的一些代码可以评估当前是否为“ NightTime”,如下所示:
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点再次打开!…)
我考虑过做一个简单的“在X处打开,为Y处睡眠”来解决这个问题……但是,如果脚本是在“打开”周期内启动的,那么直到下一次运行它才会启动。但这似乎是最简单的选择!:)
我希望有某种很棒的模块可以完成所有这些工作…:D
Python2.7-3.2的兼容性对我来说也很重要!
您的代码有点混乱。我会做这样的事情:
import datetime DAY, NIGHT = 1, 2 def check_time(time_to_check, on_time, off_time): if on_time > off_time: if time_to_check > on_time or time_to_check < off_time: return NIGHT, True elif on_time < off_time: if time_to_check > on_time and time_to_check < off_time: return DAY, True elif time_to_check == on_time: return None, True return None, False on_time = datetime.time(23,30) off_time = datetime.time(4,15) timenow = datetime.datetime.now().time() current_time = datetime.datetime.now().time() when, matching = check_time(current_time, on_time, off_time) if matching: if when == NIGHT: print("Night Time detected.") elif when == DAY: print("Day Time detected.")