运行下面代码from datetime import datetime, date import openpyxl # 加载Excel文件 workbook = openpyxl.load_workbook("your_file.xlsx") sheet = workbook.active # 获取当前日期 current_date = date.today() # 遍历日期列 for cell in sheet["A"]: # 将单元格的值转换为日期对象 cell_date = cell.value.date() # 计算日期差异 date_difference = current_date - cell_date # 输出日期差异 print(f"Date Difference: {date_difference.days} days"),提示 'str' object has no attribute 'date'

时间: 2024-04-16 20:24:19 浏览: 20
这个错误提示说明单元格的值不是一个日期对象,而是一个字符串对象。因此,在将字符串转换为日期对象之前,你需要先对其进行适当的处理。 下面的代码展示了如何处理这个问题: ```python from datetime import datetime, date import openpyxl # 加载Excel文件 workbook = openpyxl.load_workbook("your_file.xlsx") sheet = workbook.active # 获取当前日期 current_date = date.today() # 遍历日期列 for cell in sheet["A"]: # 将单元格的值转换为日期对象 if isinstance(cell.value, str): cell_date = datetime.strptime(cell.value, "%Y-%m-%d").date() else: cell_date = cell.value.date() # 计算日期差异 date_difference = current_date - cell_date # 输出日期差异 print(f"Date Difference: {date_difference.days} days") ``` 在上述代码中,我们首先检查单元格的值是否为字符串类型。如果是字符串类型,我们使用`strptime()`函数将其转换为日期对象;如果不是字符串类型,我们假设它已经是日期对象。 通过这种方式,我们可以处理字符串和已经是日期对象的情况,以计算日期差异并输出结果。 希望对你有帮助!如果还有其他问题,请随时提问。

相关推荐

#!/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()

def refresh_labels(self): data4 = self.la # 连接到 SQLite 数据库文件,并创建游标对象 cursor() conn = sqlite3.connect(filepath) cursor = conn.cursor() data41 = str(self.la) if not data4.endswith('.xlsx'): data4 += '.xlsx' wo = pinjie filepath = os.path.join(wo, data4) if not os.path.exists(filepath): wb = openpyxl.Workbook() wb.save(filepath) else: wb = openpyxl.load_workbook(filepath) for i, sheet_name in enumerate(self.sheet_names): label = tk.Label(self.unique_listbox, text=sheet_name) label.grid(row=i // 3, column=i % 3, sticky="ew", padx=1, pady=1) current_time = datetime.datetime.now().time() start_time_1 = datetime.time(8, 0, 0) # 早上8点 end_time_1 = datetime.time(20, 0, 0) # 下午7点 start_time_2 = datetime.time(20, 0, 0) # 晚上8点 end_time_2 = datetime.time(7, 0, 0) # 早上7点 for i, sheet_name in enumerate(self.sheet_names): filtered_rows = [] # 优化第二段代码:检查文件是否存在 filepath = os.path.join(pinjie, self.la + '.xlsx') if os.path.exists(filepath): workbook = xl.load_workbook(filepath) sheet = workbook.active today = datetime.datetime.now().strftime('%Y/%m/%d') cell_value = sheet.cell(row=1, column=1).value if cell_value is not None and cell_value != '': for row in sheet.iter_rows(min_row=1): if row[2].value == today and row[8].value == sheet_name: datetime_obj = datetime.datetime.strptime(row[3].value, '%H:%M:%S') row_time = datetime_obj.time() if start_time_1 <= row_time <= end_time_1 and start_time_1 <= current_time <= end_time_1: filtered_rows.append(row) elif start_time_2 <= row_time or current_time <= end_time_2: filtered_rows.append(row) label = self.unique_listbox.grid_slaves(row=i // 3, column=i % 3)[0] if filtered_rows: label.config(text=f"{sheet_name} - 已點檢", fg="green") else: label.config(text=f"{sheet_name} - 未點檢", fg="red")什麽意思

def load_excel(self, filename, menu_label, selected_label_text): for widget in self.sheet_frame.winfo_children(): widget.destroy() for widget in self.unique_listbox.winfo_children(): widget.destroy() self.la = menu_label self.workbook = xl.load_workbook(filename) self.sheet_names = sorted(self.workbook.sheetnames) # 按工作表名称从小到大排序 self.selected_label.config(text=selected_label_text) # 更新选中标签文本 data4 = self.la if not data4.endswith('.xlsx'): data4 += '.xlsx' # 拼接完整的文件路径 wo = pinjie filepath = os.path.join(wo, data4) print(filepath) # 判断文件是否存在,如果存在则打开,否则创建一个新的 Excel 文件 if os.path.exists(filepath): wb = openpyxl.load_workbook(filepath) print(f'{filepath}文件存在...') else: wb = openpyxl.Workbook() print(f'{filepath}創建好了') ws = wb.active wb.save(filepath) # 在右下側添加文本標簽 for i, sheet_name in enumerate(self.sheet_names): print(sheet_name) filtered_rows = [] # 打开文件并筛选当天日期 if os.path.exists(filepath):#判断 Excel 文件是否存在。 workbook = xl.load_workbook(filepath)#打开 Excel 文件。 label = tk.Label(self.unique_listbox, text=sheet_name) # 在右下側添加文本標簽 if filtered_rows: label.config(text=f"{sheet_name} - 已點檢") else: label.config(text=f"{sheet_name} - 未點檢") label.grid(row=i // 5, column=i % 5, sticky="ew", padx=1, pady=1)修改這段代碼,打開filepath文件在第3列篩選出當天日期,然後用獲取另一個工作薄中所有的工作表名去匹配filepath文件第九列的内容,如果有相同内容就將獲取的工作表名添加到右側下面的文本框中,并在後面添加已點檢,沒有内容就寫上未點檢添加到文本框中

def load_excel(self, filename, menu_label, selected_label_text): self.la = menu_label self.workbook = xl.load_workbook(filename) self.sheet_names = sorted(self.workbook.sheetnames) # 按工作表名称从小到大排序 self.selected_label.config(text=selected_label_text) # 更新选中标签文本 data4 = self.la if not data4.endswith('.xlsx'): data4 += '.xlsx' # 拼接完整的文件路径 wo=r'\pcq-smt-ftp01\smt$\CQ SMT-單板測試課\2.生產組\點檢表\點檢歷史資料' filepath = os.path.join(wo, data4) print(filepath) # 判断文件是否存在,如果存在则打开,否则创建一个新的 Excel 文件 if os.path.exists(filepath): wb = openpyxl.load_workbook(filepath) print(f'{filepath}文件存在...') else: wb = openpyxl.Workbook() print(f'{filepath}創建好了') # 获取工作表并保存 ws = wb.active wb.save(filepath) # 清空左侧面板 for widget in self.sheet_frame.winfo_children(): widget.destroy() # 清空右下側面板 for widget in self.unique_listbox.winfo_children(): widget.destroy() # 在右下側添加文本標簽 for i, sheet_name in enumerate(self.sheet_names): label = tk.Label(self.unique_listbox, text=sheet_name) # 打开文件并筛选当天日期 workbook = xl.load_workbook(filepath) for sheet_name in self.sheet_names: sheet = workbook.active today = datetime.datetime.now().strftime('%Y/%m/%d') filtered_rows = [] for row in sheet.iter_rows(min_row=3): if row[2].value == today and row[8].value == sheet_name: filtered_rows.append(row) # 在右下側添加文本標簽 label = tk.Label(self.unique_listbox, text=sheet_name) if filtered_rows: label.config(text=f"{sheet_name} - 已點檢") else: label.config(text=f"{sheet_name} - 未點檢") label.grid(row=i // 5, column=i % 5, sticky="ew", padx=1, pady=1)這個代碼中爲什麽只比對了一個工作表,需要修改為所有工作表

def refresh_labels(self): data4 = self.la # 连接到 SQLite 数据库文件,并创建游标对象 cursor() conn = sqlite3.connect(filepath) cursor = conn.cursor() data41 = str(self.la) if not data4.endswith('.xlsx'): data4 += '.xlsx' wo = pinjie filepath = os.path.join(wo, data4) if not os.path.exists(filepath): wb = openpyxl.Workbook() wb.save(filepath) else: wb = openpyxl.load_workbook(filepath) for i, sheet_name in enumerate(self.sheet_names): label = tk.Label(self.unique_listbox, text=sheet_name) label.grid(row=i // 3, column=i % 3, sticky="ew", padx=1, pady=1) current_time = datetime.datetime.now().time() start_time_1 = datetime.time(8, 0, 0) # 早上8点 end_time_1 = datetime.time(20, 0, 0) # 下午7点 start_time_2 = datetime.time(20, 0, 0) # 晚上8点 end_time_2 = datetime.time(7, 0, 0) # 早上7点 for i, sheet_name in enumerate(self.sheet_names): filtered_rows = [] # 优化第二段代码:检查文件是否存在 filepath = os.path.join(pinjie, self.la + '.xlsx') if os.path.exists(filepath): workbook = xl.load_workbook(filepath) sheet = workbook.active today = datetime.datetime.now().strftime('%Y/%m/%d') cell_value = sheet.cell(row=1, column=1).value if cell_value is not None and cell_value != '': for row in sheet.iter_rows(min_row=1): if row[2].value == today and row[8].value == sheet_name: datetime_obj = datetime.datetime.strptime(row[3].value, '%H:%M:%S') row_time = datetime_obj.time() if start_time_1 <= row_time <= end_time_1 and start_time_1 <= current_time <= end_time_1: filtered_rows.append(row) elif start_time_2 <= row_time or current_time <= end_time_2: filtered_rows.append(row) label = self.unique_listbox.grid_slaves(row=i // 3, column=i % 3)[0] if filtered_rows: label.config(text=f"{sheet_name} - 已點檢", fg="green") else: label.config(text=f"{sheet_name} - 未點檢", fg="red")將這段代碼重拼接的excel修改為sqlite3,然後將在這個excel所作的操作,修改為到sqlite3中,其他判斷條件不變,和顯示需求不變

def load_excel(self, filename, menu_label, selected_label_text): self.la = menu_label self.workbook = xl.load_workbook(filename) self.sheet_names = sorted(self.workbook.sheetnames) # 按工作表名称从小到大排序 self.selected_label.config(text=selected_label_text) # 更新选中标签文本 data4 = self.la if not data4.endswith('.xlsx'): data4 += '.xlsx' # 拼接完整的文件路径 wo=r'\\pcq-smt-ftp01\smt$\CQ SMT-單板測試課\2.生產組\點檢表\點檢歷史資料' filepath = os.path.join(wo, data4) print(filepath) # 清空左侧面板 for widget in self.sheet_frame.winfo_children(): widget.destroy() # 清空右下側面板 for widget in self.unique_listbox.winfo_children(): widget.destroy() # 在右下側添加文本標簽 for i, sheet_name in enumerate(self.sheet_names): label = tk.Label(self.unique_listbox, text=sheet_name) # 打开文件并筛选当天日期 workbook = xl.load_workbook(filepath) for sheet_name in self.sheet_names: sheet = workbook.active today = datetime.datetime.now().strftime('%Y/%m/%d') filtered_rows = [] for row in sheet.iter_rows(min_row=3): if row[2].value == today and row[8].value == sheet_name: filtered_rows.append(row) # 在右下側添加文本標簽 label = tk.Label(self.unique_listbox, text=sheet_name) if filtered_rows: label.config(text=f"{sheet_name} - 已點檢") else: label.config(text=f"{sheet_name} - 未點檢") label.grid(row=i // 5, column=i % 5, sticky="ew", padx=1, pady=1)這句代碼中需要修改為所有工作表名稱去比對

最新推荐

recommend-type

电影票房.csv

电影票房
recommend-type

ASP.NET技术在网站开发设计中的研究与开发(论文+源代码+开题报告)【ASP】.zip

ASP.NET技术在网站开发设计中的研究与开发(论文+源代码+开题报告)【ASP】
recommend-type

WebShell-Password.txt

WebShell-Password
recommend-type

基于 Unet++ 对自动驾驶车道线分割实战【包含数据集、完整代码、训练好的结果】

基于 UnetPlusPlus 网络自动驾驶车道线分割实战 代码均为手写,全网无重复,训练自己数据很简单,只需要摆放好数据即可,具体参考README文件,小白均可使用 代码详细介绍:https://blog.csdn.net/qq_44886601/article/details/138858574 数据集:自动驾驶车道线分割(2类别,约3200张数据和标注图像) 网络仅仅测试30个epoch,全局像素点的准确度达到0.995,精确度为0.907,召回率为0.908,dice为0.91,训练epoch加大的话,性能还会更加优越! 代码介绍: 训练过程提供了多种优化器选择(Adam、SGD、RMSProp),损失函数采用BCE 逻辑损失,学习率的衰减提供了常规恒定lr、余弦退火算法、以及step学习率衰减。可以自行选择 【训练过程会生成最好和最后一个权重,以及数据预处理完的可视化效果图、dice、loss曲线、训练日志等等】
recommend-type

zigbee-cluster-library-specification

最新的zigbee-cluster-library-specification说明文档。
recommend-type

管理建模和仿真的文件

管理Boualem Benatallah引用此版本:布阿利姆·贝纳塔拉。管理建模和仿真。约瑟夫-傅立叶大学-格勒诺布尔第一大学,1996年。法语。NNT:电话:00345357HAL ID:电话:00345357https://theses.hal.science/tel-003453572008年12月9日提交HAL是一个多学科的开放存取档案馆,用于存放和传播科学研究论文,无论它们是否被公开。论文可以来自法国或国外的教学和研究机构,也可以来自公共或私人研究中心。L’archive ouverte pluridisciplinaire
recommend-type

MATLAB结构体与对象编程:构建面向对象的应用程序,提升代码可维护性和可扩展性

![MATLAB结构体与对象编程:构建面向对象的应用程序,提升代码可维护性和可扩展性](https://picx.zhimg.com/80/v2-8132d9acfebe1c248865e24dc5445720_1440w.webp?source=1def8aca) # 1. MATLAB结构体基础** MATLAB结构体是一种数据结构,用于存储和组织相关数据。它由一系列域组成,每个域都有一个名称和一个值。结构体提供了对数据的灵活访问和管理,使其成为组织和处理复杂数据集的理想选择。 MATLAB中创建结构体非常简单,使用struct函数即可。例如: ```matlab myStruct
recommend-type

详细描述一下STM32F103C8T6怎么与DHT11连接

STM32F103C8T6可以通过单总线协议与DHT11连接。连接步骤如下: 1. 将DHT11的VCC引脚连接到STM32F103C8T6的5V电源引脚; 2. 将DHT11的GND引脚连接到STM32F103C8T6的GND引脚; 3. 将DHT11的DATA引脚连接到STM32F103C8T6的GPIO引脚,可以选择任一GPIO引脚,需要在程序中配置; 4. 在程序中初始化GPIO引脚,将其设为输出模式,并输出高电平,持续至少18ms,以激活DHT11; 5. 将GPIO引脚设为输入模式,等待DHT11响应,DHT11会先输出一个80us的低电平,然后输出一个80us的高电平,
recommend-type

JSBSim Reference Manual

JSBSim参考手册,其中包含JSBSim简介,JSBSim配置文件xml的编写语法,编程手册以及一些应用实例等。其中有部分内容还没有写完,估计有生之年很难看到完整版了,但是内容还是很有参考价值的。
recommend-type

"互动学习:行动中的多样性与论文攻读经历"

多样性她- 事实上SCI NCES你的时间表ECOLEDO C Tora SC和NCESPOUR l’Ingén学习互动,互动学习以行动为中心的强化学习学会互动,互动学习,以行动为中心的强化学习计算机科学博士论文于2021年9月28日在Villeneuve d'Asq公开支持马修·瑟林评审团主席法布里斯·勒菲弗尔阿维尼翁大学教授论文指导奥利维尔·皮耶昆谷歌研究教授:智囊团论文联合主任菲利普·普雷教授,大学。里尔/CRISTAL/因里亚报告员奥利维耶·西格德索邦大学报告员卢多维奇·德诺耶教授,Facebook /索邦大学审查员越南圣迈IMT Atlantic高级讲师邀请弗洛里安·斯特鲁布博士,Deepmind对于那些及时看到自己错误的人...3谢谢你首先,我要感谢我的两位博士生导师Olivier和Philippe。奥利维尔,"站在巨人的肩膀上"这句话对你来说完全有意义了。从科学上讲,你知道在这篇论文的(许多)错误中,你是我可以依