-2

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?

martineau
  • 119,623
  • 25
  • 170
  • 301
max07
  • 141
  • 2
  • 16
  • 1
    Well, what didn't work about the code example you posted already? Depending on which side of the "between" you want, it's either that or the negation of that. – wim Jun 19 '17 at 23:27
  • It will return 'false' as a result – max07 Jun 19 '17 at 23:31

2 Answers2

2

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')
0
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())
  • Users find it difficult to understand code only answers with no explanation. Please add some description explaining what is does and how it solves the problem or add comments in the source code at appropriate places. – Azhar Khan Feb 13 '23 at 09:59