Dalton Johnson
Dalton Johnson

Reputation: 13

Using an if statement involving time in python

So I've been trying to get an if statement to run if it is a certain time, and been trying this:

import datetime
try:
    while True:
        if(datetime.datetime.now().time() == (6, 20, 0, 0)):
            print("It's 6:20!")
except :
    pass

But nothing happens at 6:20.. why and how do I fix this?

Upvotes: 1

Views: 14500

Answers (1)

chepner
chepner

Reputation: 530853

The function you are calling doesn't return a tuple; it returns a datetime.time instance. Also, the odds of you calling the function at exactly 6:20 are vanishingly small.

success = False
while True:
    now = datetime.datetime.now().time()
    if now.hour == 6 and now.minute == 20:
        success = True
        print("It's 6:20!")

More than likely, you simply want to break out of the loop once success becomes true, meaning your code would look more like

while True:
    now = ...
    if now.hour == 6 ...:
        print("It's 6:20!")
        break

Upvotes: 1

Related Questions