How to check if time is in the range between two days?

Question:

I found some nice examples to check, if a time is in a specific range, like this one:

now_time = datetime.datetime.now().time()   
start = datetime.time(17, 30)
end = datetime.time(4, 00)
if start <= now_time <= end:

In my case, I want to check, if the current time is between 17:30 and 04 in the morning. How am I able to solve this?

Asked By: max07

||

Answers:

17:30 comes after 4:00, so anything with start <= x <= end will evaluate to false, because it implies that end (4:00) is larger than start (17:30), which is never true.

What you must do instead is check whether it’s past 17:30 or it’s before 4:00:

import datetime

now_time = datetime.datetime.now().time()
start = datetime.time(17, 30)
end = datetime.time(4, 00)
if now_time >= start or now_time <= end:
    print('true')
else:
    print('false')
from datetime import datetime, time
   
 def time_in_range(start, end, current):
        # during two days
        if (start >= end):
            if(current >= start or current <= end) :
                print("true")
            else:
                print("false")
        # during one day     
        if(start <= end):
            if(current >= start and current <= end) :
                print("true")
            else:
                print("false")

time_in_range(time(15,0),time(1,0), datetime.now().time())
Answered By: Lukasz Skiba
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.