python - 虽然循环没有破坏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()
推荐阅读
- html - 你如何让导航栏与标志平行?
- python - 有没有办法创建一个可以用作计数器的列表?
- java - intent.putExtra() 和 intent.getStringExtra() 不起作用。getStringExtra 返回 null
- android - Kotest 在 testDebugUnitTest 任务迁移到 4.0.0-BETA1 后冻结
- ios - '[ResponseData]' 到预期的参数类型'ResponseData'
- deep-learning - 为什么批量归一化在计算均值和方差时不会停止梯度?
- r - 当我们在 R 中计算 ARIMA 模型时,如何解决标准误差、z 和 pr 值的 NA 值?在 sqrt(diag(x$var.coef)) 中:产生了 NaN
- html - 使用 Bootstrap 时,Angular 组件不透明度不再起作用
- json - 解组 JSON 时的零日期
- haskell - 定义 Haskell Fibonacci 时的堆栈溢出