繁体   English   中英

虽然循环不会破坏 python

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM