【发布时间】:2021-12-19 04:15:46
【问题描述】:
我目前正在尝试编写一个脚本来检查当前日期和时间是否等于文件中的日期和时间。但是由于某些奇怪的原因,我的主 if 语句仅在调用 > 运算符时被触发,这意味着当前日期和时间必须大于文件中的日期和时间才能触发主 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
我做错了什么吗?如果是这样,如果有人能向我解释我做错了什么并帮助我解决这个问题,我会很高兴:)
提前感谢您的每一个帮助和建议:)
PS:欢迎提问:)
【问题讨论】:
-
当你能发现异常时,打印出来而不是完全忽略它。我认为至少有一个问题是显而易见的。
-
还不清楚为什么要从文件中读取多行。有多次吗?如果有多次会发生什么。同时 line 是一个字符串, ga 是一个日期时间,但是你在他们两个上都调用了 strptime。但实际上,永远不要忽略一个错误,除非它是一个非常具体的错误。
-
@FrankYellin 这只是一个 Traceback,因为文件在读取和处理时有时是空的。
-
@FrankYellin 但文件中只有一个值
-
@FrankYellin 你对如何解决这个问题有什么想法吗?
标签: python python-3.x datetime operators