【问题标题】:equal operator is not operating the way it should Python相等运算符没有按照 Python 应有的方式运行
【发布时间】: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


【解决方案1】:

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

>>> 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

【讨论】:

  • 感谢@Jan Wilamowski 这为我解决了这个问题:)
  • 是的。我希望他们能自己解决这个问题。主要问题是 try/except,它隐藏了错误。
  • @FrankYellin 是的,这本质上只是调试帮助。我开始写评论,但意识到它太大了。
猜你喜欢
  • 1970-01-01
  • 2019-06-22
  • 2013-05-06
  • 2012-07-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多