查看当前时间是否在发言10:30 AM和讲话之间的最佳方式是什么4:30 PM。
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"
请让我知道如果这是正确的方法,可以写出更好的东西吗?
我最初的答案非常具体地针对所提出的问题,并且不适应午夜的时间范围。由于六年后这仍然是公认的答案,因此我在下面合并了@rouble的答案,该答案在我的文档中得到扩展以支持午夜。
from datetime import datetime, time def is_time_between(begin_time, end_time, check_time=None): # If check time is not given, default to current UTC time check_time = check_time or datetime.utcnow().time() if begin_time < end_time: return check_time >= begin_time and check_time <= end_time else: # crosses midnight return check_time >= begin_time or check_time <= end_time # Original test case from OP is_time_between(time(10,30), time(16,30)) # Test case when range crosses midnight is_time_between(time(22,0), time(4,00))
我仍然坚持下面的原始意见,即该逻辑的大多数应用程序可能更适合于datetime无论如何都将午夜反映为日期更改的对象。
datetime