我目前正在嘗試撰寫一個腳本,用于檢查當前日期和時間是否等于檔案中的日期和時間。但是出于某種奇怪的原因,我的主要 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:歡迎提問:)
uj5u.com熱心網友回復:
似乎比較永遠不會發生,因為在此之前發生了例外:
>>> 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檔案中的字串資料。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/351667.html
上一篇:日期時間格式問題Python
下一篇:Python日期時間時區轉換
