Python TypeError:';的操作数类型不受支持;datetime.datetime';和';str';

Python TypeError:';的操作数类型不受支持;datetime.datetime';和';str';,python,python-3.x,python-3.9,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.j

我正在尝试使用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' 
回溯(最近一次呼叫最后一次):
文件“C:\Users\samsung\AppData\Local\Programs\Python\Python39\checknetwork1.py”,第行
64,在
停机时间=计算停机时间(停机时间、停机时间)
文件“C:\Users\samsung\AppData\Local\Programs\Python\Python39\checknetwork1.py”,第29行,计算时间
时差=停止-启动
TypeError:-:“datetime.datetime”和“str”的操作数类型不受支持

请帮助解决此错误。我无法找出错误的位置以及如何更正。

变量
down\u time
最初设置为type
datetime。datetime
up\u time
变量一样。问题出在
循环中,对
计算时间()
的第一次调用返回一个
str
,该str被分配到
下一次循环中调用时,该类型将不起作用


我不完全确定循环试图完成什么,但如果您想保持这种模式,您需要
calculate\u time
返回
datetime.datetime
对象,并在需要打印或记录时显式将其强制转换为
str

down\u time=calculate\u time(down\u time,up\time)
-
计算时间
返回字符串。您正在将其分配给
停机时间
。然后在随后的循环迭代中,您将返回到
计算时间