Reputation: 515
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
Upvotes: 0
Views: 1828
Reputation: 2402
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
Upvotes: 1