-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
  • 112,593
  • 23
  • 157
  • 280
max07
  • 111
  • 2
  • 14
  • 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

1 Answers1

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