类型错误:不支持的操作数类型 -:'datetime.datetime' 和 'str'

时间:2021-06-04 13:58:57

标签: python python-3.x python-3.9

我正在尝试使用 python 构建一个网络监视器,它通过向外部资源发送 ping 请求来持续监视 Internet 连接。它还保留互联网何时关闭和停机持续时间的日志。运行此 python 程序时,出现错误。

    import socket
    import time
    import datetime
    import os
    import sys
        
    LOG_FNAME = "network.log"
    FILE = os.path.join(os.getcwd(), LOG_FNAME)
    def send_ping_request(host="1.1.1.1", port=53, timeout=3):
        try:
            socket.setdefaulttimeout(timeout)
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.connect((host,port))
        except OSError as error:
            return False
        else:
            s.close()
            return True
    def write_permission_check():
        try:
            with open(FILE, "a") as file:
                pass
        except OSError as error:
            print("Log file creation failed")
            sys.exit()
        finally:
            pass

    def calculate_time(start, stop):
        time_difference = stop - start
        seconds = float(str(time_difference.total_seconds()))
        return str(datetime.timedelta(seconds=seconds)).split(".")[0]
    def mon_net_connection(ping_freq=2):
        monitor_start_time = datetime.datetime.now()
    def motd():
        motd = "Network connection monitoring started at: " + 
    str(monitor_start_time).split(".")[0] + " Sending ping request in " + str(ping_freq) + " seconds"
        print(motd)

    with open(FILE, "a") as file:
        file.write("\n")
        file.write("motd" + "\n")
    while True:
        if send_ping_request():
            time.sleep(1)
        else:
            down_time = datetime.datetime.now()
            fail_msg = "Network Connection Unavailable at: " +str(down_time).split(".")[0]
            print(fail_msg)
            with open(FILE, "a") as file:
                file.write(fail_msg + "\n")
                i = 0
            while not send_ping_request():
                time.sleep(1)
                i += 1
                if i >= 3600:
                    i = 0
                    now = datetime.datetime.now()
                    continous_message = "Network Unavailabilty Persistent at: " +str(now).split(".")[0]
                    print(continous_message)
                    with open(FILE, "a") as file:
                        file.write(continous_message + "\n")
                up_time = datetime.datetime.now()
                uptime_message = "Network Connectivity Restored at: " +str(up_time).split(".")[0]
 
                down_time = calculate_time(down_time, up_time)
                _m = "Network Connection was Unavailable for " + down_time
 
                print(uptime_message)
                print(_m)
 
                with open(FILE, "a") as file:
                    file.write(uptime_message + "\n")
                    file.write(_m + "\n")
        mon_net_connection()

我得到的错误如下。

    Traceback (most recent call last):
      File "C:\Users\samsung\AppData\Local\Programs\Python\Python39\checknetwork1.py", line 
    64, in <module>
        down_time = calculate_time(down_time, up_time)
      File "C:\Users\samsung\AppData\Local\Programs\Python\Python39\checknetwork1.py", line 29, in calculate_time
        time_difference = stop - start
    TypeError: unsupported operand type(s) for -: 'datetime.datetime' and 'str' 

请帮助解决此错误。我无法弄清楚错误在哪里,以及如何纠正它。

1 个答案:

答案 0 :(得分:0)

down_time 变量最初设置为 datetime.datetime 类型,up_time 变量也是如此。问题出在您的 while 循环中,对 calculate_time() 的第一次调用返回一个 str,该 down_time 被分配给 calculate_time,因此下次您在循环中调用它时,类型将不起作用。

我不完全确定循环试图完成什么,但如果您想保持这种模式,您需要 datetime.datetime 返回一个 str 对象并将其显式转换为 {{1} } 当您需要打印或记录时。