0

I am trying to compare two datetime times in a while loop in python and when they are equal I want to break out of the loop

I have created a while loop and in it I have an if statement that compares the two datetime times together. The problem is that the if statement doesn't execute

d=datetime.datetime.strptime('01:26:00','%H:%M:%S')
dnow=datetime.datetime.now()

while True:
    time.sleep(1)
    if(dnow.time() != d.time()):
        print(datetime.datetime.now())
    else:
        print('Hello World')
        break

I am expecting when dnow.time() equals d.time() then the else statement gets executed. Print out of the program 2019-07-30 01:25:54.422644 2019-07-30 01:25:55.423967 2019-07-30 01:25:56.425256 2019-07-30 01:25:57.426535 2019-07-30 01:25:58.427819 2019-07-30 01:25:59.429103 2019-07-30 01:26:00.429910 2019-07-30 01:26:01.431201 2019-07-30 01:26:02.432484 2019-07-30 01:26:03.434393 2019-07-30 01:26:04.434830

4
  • 2
    time goes so fast - it is hard to get equal time - better check >= or <= instead of == or != Commented Jul 29, 2019 at 23:18
  • tried <= but it didn't work Commented Jul 29, 2019 at 23:28
  • 1
    You're comparing against the same value on every iteration of the loop; you probably want to get rid of dnow and just check if (datetime.datetime.now() >= d) Commented Jul 29, 2019 at 23:33
  • then maybe you need >=. And display d and dnow to see what you have. maybe you have different dates - ie. 01.01.1970 ? Commented Jul 29, 2019 at 23:34

1 Answer 1

1

1st problem:

Since you're waiting one second on each loop, I assume you want the comparison to be accurate to one second. Comparing the raw output of time() won't work, as the microsecond component will almost never match.

This loop breaks if the hour, minute, and second match, but ignores microseconds.

2nd problem:

In your code, you're only defining dnow once, so dnow.time() never changes. You need to define dnow within the loop.

Try this:

d=datetime.datetime.strptime('01:59:00','%H:%M:%S').time()

while True:
    time.sleep(1)
    now = datetime.datetime.now().time()
    if(now.hour != d.hour or now.minute != d.minute or now.second != d.second):
        print(datetime.datetime.now())
    else:
        print('Hello World')
        break
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.