63

10:30 AM查看当前时间是否介于 say和之间的最佳方法是什么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"

请让我知道这是否是正确的方法,可以写更好的东西吗?

4

8 回答 8

109

我最初的答案非常具体地集中在提出的问题上,并且不适应跨越午夜的时间范围。由于 6 年后这仍然是公认的答案,因此我在下面合并了@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那些跨越午夜被反映为日期变化的对象。

于 2012-04-06T19:28:23.897 回答
55

上述接受的解决方案不适用于通宵时间,这是:

import datetime as dt  
def isNowInTimePeriod(startTime, endTime, nowTime): 
    if startTime < endTime: 
        return nowTime >= startTime and nowTime <= endTime 
    else: 
        #Over midnight: 
        return nowTime >= startTime or nowTime <= endTime 

#normal example: 
isNowInTimePeriod(dt.time(13,45), dt.time(21,30), dt.datetime.now().time())

#over midnight example: 
isNowInTimePeriod(dt.time(20,30), dt.time(1,30), dt.datetime.now().time())
于 2016-08-08T19:16:57.097 回答
14

这是@rouble回答的小例子:

from datetime import datetime

def isNowInTimePeriod(startTime, endTime, nowTime):
    if startTime < endTime:
        return nowTime >= startTime and nowTime <= endTime
    else: #Over midnight
        return nowTime >= startTime or nowTime <= endTime


timeStart = '3:00PM'
timeEnd = '11:00AM'
timeNow = '2:59AM'
timeEnd = datetime.strptime(timeEnd, "%I:%M%p")
timeStart = datetime.strptime(timeStart, "%I:%M%p")
timeNow = datetime.strptime(timeNow, "%I:%M%p")

print(isNowInTimePeriod(timeStart, timeEnd, timeNow))
于 2017-01-24T09:33:14.967 回答
4

我的 2 美分,它对我有用,而且很容易

while True:
    now = datetime.now()
    current_time = now.strftime("%H:%M:%S")
    start = '19:19:00'
    end = '19:19:20'
    if current_time > start and current_time < end:
        print('in')
        print(current_time)
        tempo.sleep(1)
    else:
        print('out')
        print(current_time)
于 2019-12-06T15:02:27.633 回答
0

看看 py-time-between 包:https ://pypi.org/project/py-time-between/

测试用例:

from datetime import time
from timebetween import is_time_between


def test_is_time_between():
    t, s, e = time(0), time(0), time(0)
    assert is_time_between(t, s, e)

    t, s, e = time(0, 0, 0, 1), time(0), time(0, 0, 0, 2)
    assert is_time_between(t, s, e)

    t, s, e = time(0, 0, 0, 1), time(0, 0, 0, 1), time(0, 0, 0, 2)
    assert is_time_between(t, s, e)

    t, s, e = time(0, 0, 0, 2), time(0, 0, 0, 1), time(0, 0, 0, 2)
    assert is_time_between(t, s, e)

    t, s, e = time(0, 0, 1), time(23, 59, 59), time(0, 0, 2)
    assert is_time_between(t, s, e)

    t, s, e = time(12, 0, 0), time(23, 59, 59), time(0, 0, 0)
    assert is_time_between(t, s, e)

    t, s, e = time(23, 59, 57), time(23, 59, 59), time(23, 59, 57)
    assert is_time_between(t, s, e)

    t, s, e = time(23, 59, 58), time(23, 59, 59), time(23, 59, 57)
    assert not is_time_between(t, s, e)

    t, s, e = time(22), time(22), time(5, 59, 59)
    assert is_time_between(t, s, e)
于 2018-09-08T14:04:07.710 回答
0

可以进一步简化:

def isNowInTimePeriod(startTime, endTime, nowTime):
    if startTime < endTime:
        return startTime <= nowTime <= endTime
    else: #Over midnight
        return nowTime >= startTime or nowTime <= endTime
于 2019-09-24T07:45:59.467 回答
0

我有一个类似的要求,我希望某个任务在每个工作日的上午 9 点到下午 3:30 之间运行。

def somefunction():
    cdate = datetime.datetime.strftime(datetime.datetime.now(), "%d-%m-%Y")
    if (0 <= time.localtime().tm_wday <= 4) and (datetime.datetime.strptime(cdate + " 09:00:00", "%d-%m-%Y %H:%M:%S") <= datetime.datetime.now() <= datetime.datetime.strptime(cdate + " 15:30:00", "%d-%m-%Y %H:%M:%S")):
         << do something >>

解释:

cdate变量以字符串格式获取当前日期。

该条件检查当前工作日是否 >= 0(星期一)和 <= 4(星期五)。它还检查当前时间datetime格式是否 >= 今天的上午 9:00,以及当前时间是否 <= 今天的 15:30。

于 2020-04-17T19:02:03.187 回答
0

可能比所选答案更接近 OP 要求的解决方案。它使用日期时间而不是时间作为要检查的对象。它还使用持续时间而不是时间来指定间隔的结束。

from datetime import datetime, time, timedelta

def is_date_within(begin_time, span_time, check_date=None):
    """                                                                                        
    Return True if given check_date is within the interval begining                            
    at begin_time with a duration of span_time.                                                
                                                                                               
    Args:                                                                                      
       - begin_time: datetime.time object                                                      
       - span_time: datetime.timedelta object                                                  
       - check_date: datetime.datetime object.                                                 
           If None, default to current UTC date                                                
    """
    check_date = check_date or datetime.utcnow()
    if check_date.time() >= begin_time:
        begin_date = check_date.combine(check_date.date(), begin_time)
    else:
        begin_date = check_date.combine(check_date.date() - timedelta(days=1),
                                        begin_time)
    return begin_date <= check_date <= begin_date + span_time

test_date = datetime(2020, 6, 22, 11, 31)
assert(is_date_within(time(10,30), timedelta(hours=4), test_date) == True)
assert(is_date_within(time(10,30), timedelta(hours=1), test_date) == False)

# Span midnight                                                                                
assert(is_date_within(time(23,30), timedelta(hours=13), test_date) == True)
assert(is_date_within(time(23,30), timedelta(hours=1), test_date) == False)
于 2020-06-23T03:31:29.017 回答