如何使用Python的datetime模块确定当前时间是否在指定范围内?

时间:2012-04-06 19:24:22

标签: python python-datetime

查看当前时间是否在10:30 AM4: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"

如果这是正确的方法,请告诉我,可以写得更好吗?

8 个答案:

答案 0 :(得分:51)

我的原始答案非常专注于提出的问题,并且不适应跨越午夜的时间范围。因为这仍然是6年后接受的答案,我已经将@ ruble的答案纳入了我的扩展,以支持午夜。

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个对象,其中横穿午夜反映为日期更改。

答案 1 :(得分:28)

接受的解决方案无法在夜间工作:

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

答案 2 :(得分:5)

这是@ ruble答案的小例子:

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))

答案 3 :(得分:0)

可以进一步简化:

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

答案 4 :(得分:0)

我的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)

答案 5 :(得分:0)

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

var count = 0; // this variable is global; it's not inside any function

$('#searchForm').on('submit', (e) => {
    e.preventDefault();
    let searchText = $('#search-box').val();
    $.ajax({
        url: "/",
        type: 'POST',
        data: { 
            input: searchText
        },
        success: function(res) {
            if(count > 0) {  // only reset if it's not the first search
                $(".resetable").html("");
            }

            count++;         // increment the count

            // other code ...
        }
    });
});

解释:

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 >> 变量以字符串格式获取当前日期。

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

答案 6 :(得分: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)

答案 7 :(得分:-1)

看看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)