【发布时间】:2023-02-09 00:14:45
【问题描述】:
我需要从 dict Dict 添加一个新行到 excel 文件,并且在这个 Dict 中我有一个日期值但是这个是像单元格 f excel 文件中的文本格式一样添加的
这是我的代码,问题在于 datetime.fromisoformat(row['Date']).strftime("%d/%m/%Y") 但它是在 excel 文件中以文本格式添加的
Declaration_dict = Excel_Dict(r"\\path_to_excel_file.xlsx")
for row in Declaration_dict:
if row['statut'] == 'OK':
line_declaration = (row['Cle_modifiee'], row['via'], row['Reference'], datetime.fromisoformat(row['Date']).strftime("%d/%m/%Y"), row['Detail'], row['NOM'], row['User'], row['Metier'], row['Equipe'], row['Libelle'])
sheet_stock.append(line_declaration)
【问题讨论】:
-
Excel 中的日期是二进制值,它们没有格式。它们使用单元格样式和最终用户的区域设置显示。使用 Python
datetime而不是尝试猜测单元格的样式或最终用户的语言环境 -
.strftime("%d/%m/%Y")几乎总是一个错误。虽然某些应用程序可以处理明确的 ISO 8601 格式 (YYYY-MM-DD),但无法确定 4/7/2023 是 4 月 7 日还是 7 月 4 日 -
此外,您发布的代码不会尝试“添加”格式。在将其转换为本地化字符串之前,它会正确读取 Excel 日期。如果不单独使用
row['Date'],则仅使用datetime.fromisoformat(row['Date'])。如果 Excel 工作表包含实际日期,row['Date']会将它们作为datetime值返回。