How do I determine if current time is within a specified range using Python's datetime module?

Question:

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?

Asked By: user993563

||

Answers:

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

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.

Answered By: Joe Holloway

The above accepted solution does not work with overnight times, this does:

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())
Answered By: rouble

here’s little example for @rouble’s answer:

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))
Answered By: Maulik

Take a look in py-time-between package: https://pypi.org/project/py-time-between/

Test cases:

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)
Answered By: Allan Silva

Can be simplified further:

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

My 2 cent, it works for me and it is easy

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)
Answered By: EVE Milano

I had a similar requirement where I wanted a certain task to run on every weekday between 9 AM and 3:30 PM.

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

explanation:

cdate variable gets current date in string format.

The condition checks if the current week day is >= 0 (Monday) and <= 4(Friday). It also checks if the current time in datetime format is >= 9:00 AM on today’s date and if current time is <= 15:30 on today’s date.

Answered By: rickydj

A solution that may be closer to OP’s request than the selected answer.
It uses datetime rather than time as the object to check against.
It also uses a duration rather than a time to specify the end of the interval.

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)
Answered By: Thomas Vincent

Here how i did it in python

import datetime    
e = datetime.datetime.now()    
current_time = (e.strftime("%I:%M:%S %p"))
if current_time < '04:30:00 PM' or current_time > '9:30 AM':
    print(current_time)
Answered By: user8214
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.