如何使用 Python 的 datetime 模块确定当前时间是否在指定范围内? [英] How do I determine if current time is within a specified range using Python's datetime module?
问题描述
查看当前时间是否介于 10:30 AM
和 4:30 PM
之间的最佳方法是什么.
What would be the best way to see if the current time lies between say 10:30 AM
and 4:30 PM
.
我能想到以下,不知道有多正确:
I could think of the following, not sure how correct:
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"
请让我知道这是否是正确的方法,可以写出更好的东西吗?
Please let me know if this the correct approach, can something better be written?
推荐答案
我最初的回答非常专注于提出的问题,并没有适应跨越午夜的时间范围.由于这仍然是 6 年后公认的答案,因此我在下面合并了@rouble 的答案,该答案在我的基础上进行了扩展以支持午夜.
My original answer focused very specifically on the question as posed and didn't accommodate time ranges that span midnight. As this is still the accepted answer 6 years later, I've incorporated @rouble's answer below that expanded on mine to support midnight.
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
对象,在这些对象中,跨越午夜被反映为日期更改.
I still stick to my original comment below that most applications of this logic would probably be better suited with datetime
objects where crossing midnight is reflected as a date change anyway.
这篇关于如何使用 Python 的 datetime 模块确定当前时间是否在指定范围内?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!