if timing >= max_d_datetime: TypeError: '>=' not supported between instances of 'datetime.datetime' and 'str'
时间: 2023-07-30 17:04:25 浏览: 41
这个错误通常是因为你在比较一个 `datetime.datetime` 类型的变量和一个字符串类型的变量。你需要将字符串类型的变量转换为 `datetime.datetime` 类型,然后再进行比较。
你可以使用 `datetime.datetime.strptime()` 函数将字符串转换为 `datetime.datetime` 类型。例如,假设你有一个字符串类型的变量 `max_d_datetime_str` 和一个 `datetime.datetime` 类型的变量 `timing`,你可以这样做:
```
import datetime
max_d_datetime_str = '2022-01-01 00:00:00'
max_d_datetime = datetime.datetime.strptime(max_d_datetime_str, '%Y-%m-%d %H:%M:%S')
timing = datetime.datetime.now()
if timing >= max_d_datetime:
print("timing is later than or equal to max_d_datetime")
else:
print("timing is earlier than max_d_datetime")
```
在这个例子中,`max_d_datetime_str` 会被转换为一个 `datetime.datetime` 类型的变量 `max_d_datetime`,然后将其与 `timing` 进行比较。
相关问题
将这段代码改为C++:import os from logging import getLogger, DEBUG, handlers, Formatter from src.config import temp, basic base_dir = basic.temp_root_dir + "/ahsg/" def log_record(log_name=None, file_name=None, file_size=None, file_bat=None): if not isinstance(log_name, str): log_name = 'logg' if not (isinstance(file_name, str) and file_name.endswith('.log')): file_name = f'{log_name}.log' if not isinstance(file_size, int): file_size = 5000000 if not isinstance(file_bat, int): file_bat = 1 __loggg = getLogger(log_name) if not __loggg.handlers: __loggg.setLevel(DEBUG) file_log = handlers.RotatingFileHandler(file_name, maxBytes=file_size, backupCount=file_bat) file_log.setFormatter(Formatter(f"%(asctime)s-['{log_name}']-%(levelname)s:%(message)s")) __loggg.addHandler(file_log) return __loggg log_report_station_behaviour = log_record('station_behaviour', base_dir + 'station_behaviour.log') log_report_timing_violation_placement = log_record('timing_violation_placement', base_dir + 'timing_violation_placement.log') log_report_region_detection = log_record('region_detection', base_dir + 'region_detection.log')
#include <iostream>
#include <string>
#include <fstream>
#include <ctime>
#include <iomanip>
#include "src/config.h"
using namespace std;
string base_dir = basic.temp_root_dir + "/ahsg/";
logger log_record(string log_name = "", string file_name = "", int file_size = 0, int file_bat = 0) {
if (log_name.empty()) {
log_name = "logg";
}
if (file_name.empty() || file_name.substr(file_name.length() - 4) != ".log") {
file_name = log_name + ".log";
}
if (file_size == 0) {
file_size = 5000000;
}
if (file_bat == 0) {
file_bat = 1;
}
logger __loggg = getLogger(log_name);
if (__loggg.handlers().empty()) {
__loggg.setLevel(DEBUG);
handlers::RotatingFileHandler file_log(file_name, maxBytes=file_size, backupCount=file_bat);
file_log.setFormatter(Formatter("%(asctime)s-['" + log_name + "']-%(levelname)s:%(message)s"));
__loggg.addHandler(file_log);
}
return __loggg;
}
logger log_report_station_behaviour = log_record("station_behaviour", base_dir + "station_behaviour.log");
logger log_report_timing_violation_placement = log_record("timing_violation_placement", base_dir + "timing_violation_placement.log");
logger log_report_region_detection = log_record("region_detection", base_dir + "region_detection.log");
int main() {
// your code here
return 0;
}
#!/usr/bin/env python #coding: utf-8 import os from time import time from datetime import datetime from netmiko import ConnectHandler from openpyxl import Workbook from openpyxl import load_workbook def read_device_excel( ): ip_list = [] wb1 = load_workbook('E:\/Users/Wayne_Peng/Desktop/cs_lab.xlsx') ws1 = wb1.get_sheet_by_name("Sheet1") for cow_num in range(2,ws1.max_row+1): ipaddr = ws1["a"+str(cow_num)].value ip_list.append(ipaddr) return ip_list def get_config(ipaddr): session = ConnectHandler(device_type="huawei", ip=ipaddr, username="mtlops", password="cisco,123", banner_timeout=300) print("connecting to "+ ipaddr) print ("---- Getting HUAWEI configuration from {}-----------".format(ipaddr)) # config_data = session.send_command('screen-length 0 temporary') # config_data = session.send_command('dis cu | no-more ') # command = 'display version | display cpu-usage | display memory-usage' # config_data = session.send_command(command) commands = ['display version', 'display cpu-usage', 'display memory-usage'] config_data = '' for cmd in commands: output = session.send_command_timing(cmd) config_data += f'{cmd}\n{output}\n' session.disconnect() return config_data def write_config_to_file(config_data,ipaddr): now = datetime.now() date= "%s-%s-%s"%(now.year,now.month,now.day) time_now = "%s-%s"%(now.hour,now.minute) #---- Write out configuration information to file config_path = 'E:\/Users/Wayne_Peng/Desktop/' +date verify_path = os.path.exists(config_path) if not verify_path: os.makedirs(config_path) config_filename = config_path+"/"+'config_' + ipaddr +"_"+date+"_" + time_now # Important - create unique configuration file name print ('---- Writing configuration: ', config_filename) with open( config_filename, "w",encoding='utf-8' ) as config_out: config_out.write( config_data ) return def main(): starting_time = time() ip_list = read_device_excel() for ipaddr in ip_list: hwconfig = get_config(ipaddr) write_config_to_file(hwconfig,ipaddr) print ('\n---- End get config threading, elapsed time=', time() - starting_time) #======================================== # Get config of HUAWEI #======================================== if __name__ == '__main__': main() 加一段gevent,def run_gevent()
好的,可以尝试这样写:
```
#!/usr/bin/env python
#coding: utf-8
import os
from time import time
from datetime import datetime
from netmiko import ConnectHandler
from openpyxl import Workbook
from openpyxl import load_workbook
import gevent
from gevent import monkey
monkey.patch_all()
def read_device_excel():
ip_list = []
wb1 = load_workbook('E:\/Users/Wayne_Peng/Desktop/cs_lab.xlsx')
ws1 = wb1.get_sheet_by_name("Sheet1")
for cow_num in range(2,ws1.max_row+1):
ipaddr = ws1["a"+str(cow_num)].value
ip_list.append(ipaddr)
return ip_list
def get_config(ipaddr):
session = ConnectHandler(device_type="huawei",
ip=ipaddr,
username="mtlops",
password="cisco,123",
banner_timeout=300)
print("connecting to "+ ipaddr)
print ("---- Getting HUAWEI configuration from {}-----------".format(ipaddr))
commands = ['display version', 'display cpu-usage', 'display memory-usage']
config_data = ''
for cmd in commands:
output = session.send_command_timing(cmd)
config_data += f'{cmd}\n{output}\n'
session.disconnect()
return config_data
def write_config_to_file(config_data,ipaddr):
now = datetime.now()
date= "%s-%s-%s"%(now.year,now.month,now.day)
time_now = "%s-%s"%(now.hour,now.minute)
#---- Write out configuration information to file
config_path = 'E:\/Users/Wayne_Peng/Desktop/' +date
verify_path = os.path.exists(config_path)
if not verify_path:
os.makedirs(config_path)
config_filename = config_path+"/"+'config_' + ipaddr +"_"+date+"_" + time_now # Important - create unique configuration file name
print ('---- Writing configuration: ', config_filename)
with open( config_filename, "w",encoding='utf-8' ) as config_out:
config_out.write( config_data )
return
def run_gevent(ip_list):
jobs = []
for ipaddr in ip_list:
jobs.append(gevent.spawn(get_config, ipaddr))
gevent.joinall(jobs)
for job, ipaddr in zip(jobs, ip_list):
hwconfig = job.value
write_config_to_file(hwconfig,ipaddr)
print('\n---- End get config threading')
def main():
starting_time = time()
ip_list = read_device_excel()
run_gevent(ip_list)
print('elapsed time:', time() - starting_time)
#========================================
# Get config of HUAWEI
#========================================
if __name__ == '__main__':
main()
```
注意,这里使用了 `gevent` 库,需要先安装。可以在命令行中使用 `pip install gevent` 进行安装。