0

I have the following code:

if date.datetime.now().strftime('%H:%M:%S') != ( date.time(hour = 23, minute = 59, second = 59) and date.time(hour = 13, minute = 35, second =01)):
    print("ok")

I want to print ok if the time is not between midnight and 1 PM 15 minutes and 1 second in the afternoon. This script works but it is not right. how can i fix this.

Slartibartfast
  • 1,058
  • 4
  • 26
  • 60
  • Does this answer your question? [How to check if the current time is in range in python?](https://stackoverflow.com/questions/10747974/how-to-check-if-the-current-time-is-in-range-in-python) – FObersteiner May 26 '20 at 11:30

3 Answers3

3

You can simplify a lot of things since you want yo check the range between time 0 and 1 PM 15 minutes.

You just have to check if the time is bigger 1 PM 15 minutes

if date.datetime.now().time() > date.time(hour = 13, minute = 35, second =1):
    print("ok")
Sylvaus
  • 844
  • 6
  • 13
2

strftime() gives you a string. you don't want that. you want to compare time / datetime objects. Ex:

from datetime import time

t0, t1 = time(0, 0, 0), time(13, 15, 1)
test = (time(1,2,3), time(19,15,30))

for t in test:
    if t0 < t <= t1:
        print(f"ok: {t}")
    else:
        print(f"not ok: {t}")

# ok: 01:02:03
# not ok: 19:15:30 
FObersteiner
  • 22,500
  • 8
  • 42
  • 72
1

Edited:

Sorry, my previous reply was wrong.

I think you are looking at range, not equality comparison. So first, you need to do comparison with your current date on each condition. So you want to translate formula 13:35:01 < current_date < 23:59:59 into code. Which means you need to compare current_date with each condition individually and run and between two. Therefore it should be like this:

current_date = date.datetime.now().strftime('%H:%M:%S')
if  current_date > date.time(hour = 23, minute = 59, second = 59) and current_date < date.time(hour = 13, minute = 35, second = 01):
    print("ok")