【问题标题】:Add a correct format date in Excel file with Python openpyxl使用 Python openpyxl 在 Excel 文件中添加正确格式的日期
【发布时间】: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 值返回。

标签: python excel openpyxl


【解决方案1】:

我只用datetime.fromisoformat(行['日期'])但我没有日期格式的单元格,单元格是标准格式

excel file result

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多