I am currently trying to write an script which is checking if the current date and time is equal to a date and time in a file. But for some weird reason my main if statement is only being triggered when calling the >
operator this means that the current date and time must be bigger than the date and time in the file to trigger the main if statement. But this is exactly what I want to avoid because at the end the script should be very precise and punctual. This operator causes also some bugs when starting my script because the function is working in a multiprocess with other functions. When callig the ==
operator instead of the >
operator the if statement is not being triggered. I wonder if my program is formatting a parameter wrong and this might cause the none equality problem.
This is my code:
#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
Is there something I am doing wrong? If so I would be very glad if someone could explain to me what I've made wrong and help me solve this problem:)
Thank's for every help and suggestion in advance:)
PS: Feel free to ask questions:)
CodePudding user response:
It seems like the comparison never happens because an exception occurs before that:
>>> 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
However, you swallow up all exceptions so you probably didn't see that. strptime
converts strings to datetime objects. You should decide whether to compare strings (in which case, format ga
properly) or datetimes (in which case, call strptime
on the string data in your file.