equal运算符没有按照Python应有的方式进行操作



我目前正在尝试编写一个脚本,检查当前日期和时间是否等于文件中的日期和时间。但出于某种奇怪的原因,只有在调用>运算符时才会触发我的main if语句,这意味着当前日期和时间必须大于文件中触发main if语句的日期和时间。但这正是我想要避免的,因为在最后脚本应该非常精确和准时。这个运算符在启动脚本时也会导致一些错误,因为该函数与其他函数在多进程中工作。当调用==运算符而不是>运算符时,没有触发if语句。我想知道我的程序是否格式化了一个参数,这可能会导致不相等的问题。

这是我的代码:

#the content of the safe_timer.txt file is for example 05.11.2021 01:05:10
#the current time is for example 05.11.2021 01:05:00. 
#The while loop should theoretically loop until ga is equal to alarm_time
#but when calling if ga==alarm_time: nothing is happening at all.
#Am I doing something wrong while formatting the two parameters?
#Or why is nothing happening when calling if ga==alarm_time:?
#ga = current time
#alarm_time = file content
#both parameters should be formated to the same format when running the script
import time
import datetime
from datetime import datetime
def background_checker():
with open('safe_timer.txt','r+') as sf_timer:
while True:
try:
formatit = '%d.%m.%Y %H:%M:%S'
if len(str(sf_timer)) > int(0):
ga = datetime.now()        
for lines in sf_timer:
alarm_time = datetime.strptime(lines, formatit)  
ga = datetime.strptime(ga, formatit)   
if ga == alarm_time: #That's the point where I am not sure what I've made wrong because ga should equal at some time alarm_time and everything should be fine. Remember that > is not a solution because this function is operating in a multiprocess and this operator is causing bugs when starting the script
print('alarm') 
except Exception as err:
continue

我做错什么了吗?如果是这样的话,如果有人能向我解释我做错了什么,并帮助我解决这个问题,我会非常高兴:(

感谢您提前提供的每一个帮助和建议:(

附言:请随意提问:(

似乎从未发生过比较,因为在此之前发生了异常:

>>> ga = datetime.now()
>>> formatit = '%d.%m.%Y %H:%M:%S'
>>> datetime.strptime(ga, formatit)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: strptime() argument 1 must be str, not datetime.datetime

然而,你吞下了所有的例外,所以你可能没有看到。strptime将字符串转换为日期时间对象。您应该决定是比较字符串(在这种情况下,正确地格式化ga(还是日期时间(在那种情况下,对文件中的字符串数据调用strptime(。

最新更新