[英]While loop is not breaking python
我目前正在嘗試將當前日期和時間與另一個文件中記錄的日期和時間進行比較。 出於某種奇怪的原因,while 循環並沒有中斷,而是創建了一個無限循環。
這是我嘗試將當前日期和時間與包含的test.txt
文件進行比較的內容: 29.10.2021 20:47:47
這是我的代碼(假設ga
等於test.txt
的數據):
import time
from datetime import datetime
from datetime import timedelta
def background_checker():
with open('test.txt','r+') as sample:
while True:
ga = datetime.now()
ga = ga.strftime('%d.%m.%Y %H:%M:%S')
print(ga, end='\r')
line = sample.readline()
if line == ga:#if time and date in file equal to the current time and date, the if statement should be triggered.
print('alarm')
break
background_checker()
我的代碼做錯了嗎? 如果是這樣,如果有人能向我解釋我做錯了什么以及我如何解決這個問題,我會很高興。
您正在嘗試創建一個警報程序,但您正在使用字符串相等性比較字符串。 更好的方法是比較日期時間對象。
import time
from datetime import datetime
from datetime import timedelta
def background_checker():
format = '%d.%m.%Y %H:%M:%S'
with open('test.txt','r+') as sample:
while True:
ga = datetime.now()
print(ga)
line = sample.readline()
alarm_time = datetime.datetime.strptime(line, format)
if ga > alarm_time: #if time and date in file equal to the current time and date, the if statement should be triggered.
print('alarm')
break
background_checker()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.