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



我正试图使用python构建一个网络监控器,该监控器通过向外部资源发送ping请求来持续监控互联网连接。它还记录了互联网何时关闭以及停机时间。在运行这个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:UserssamsungAppDataLocalProgramsPythonPython39checknetwork1.py", line 
64, in <module>
down_time = calculate_time(down_time, up_time)
File "C:UserssamsungAppDataLocalProgramsPythonPython39checknetwork1.py", line 29, in calculate_time
time_difference = stop - start
TypeError: unsupported operand type(s) for -: 'datetime.datetime' and 'str' 

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

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

我不完全确定循环试图实现什么,但如果你想维护这个模式,你需要calculate_time返回一个datetime.datetime对象,并在你需要打印或记录它时显式地将其转换为str

最新更新