首页 > 解决方案 > 虽然循环没有破坏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()

我在我的代码中做错了吗?如果是这样,如果有人能向我解释我做错了什么以及如何解决这个问题,我会很高兴。

标签: pythonpython-3.xdatetimetime

解决方案


您正在尝试创建一个警报程序,但您正在使用字符串相等性比较字符串。更好的方法是比较日期时间对象。

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()

推荐阅读