【问题标题】:Pandas: Write dates to Excel such that they are useable as DatesPandas:将日期写入 Excel,以便它们可用作日期
【发布时间】:2021-09-19 00:19:29
【问题描述】:

我无法让输出的 XLSX 以可用的方式写入日期,并且我遵循了以下熟悉的线程:

https://xlsxwriter.readthedocs.io/example_pandas_datetime.html

Problem with Python Pandas data output to excel in date format

这是一个 MWE:

import pandas as pd
import xlsxwriter

not_in1 = ['missing']
# generate data
df = pd.DataFrame({'date1': ['5/1/2022 00:33:22', '3/1/2022 00:33:22', 'missing'], 'date2': ['3/1/2022 00:33:22', 'missing', '6/2/2022 00:33:22']})
# format
df['date1'] = df['date1'].apply(lambda x: pd.to_datetime(x).strftime('%m/%d/%Y') if x not in not_in1 else x)
df['date2'] = df['date2'].apply(lambda x: pd.to_datetime(x).strftime('%m/%d/%Y') if x not in not_in1 else x)

# write
path = 'C:\\Users\\Andrew\\Desktop\\xd2.xlsx'
with pd.ExcelWriter(path, engine='xlsxwriter', date_format="mm dd yyyy", datetime_format="mm dd yyyy") as writer:
    df.to_excel(writer, sheet_name='Sheet1', index=False)
    workbook  = writer.book
    worksheet = writer.sheets['Sheet1']
    formatdict = {'num_format':'mm/dd/yyyy'}
    fmt = workbook.add_format(formatdict)
    worksheet.set_column('A:B', 20, fmt)

这里作为 XLSX,Excel 不知道该怎么做:

https://i.stack.imgur.com/PBrAi.png

有趣的是,如果我将 XLSX 工作表保存为 CSV,日期就可以正常工作。

https://i.stack.imgur.com/tROFc.png

【问题讨论】:

  • 我认为从字符串到日期时间的strftime() 转换在您的示例中不起作用。输出 Excel 文件中日期的数据类型是字符串,而不是日期/数字。此外,在 Python 中,类型仍然是字符串,如果您执行type(df['date1'][0]),您可以看到它。这将在转换前后给出<type 'str'>

标签: python excel pandas


【解决方案1】:

您的 lambda 函数将 x 参数转换为字符串,您应该将其保留为日期时间。目前,您在 Excel 中以字符串结尾(使用 Excel 的 type 查看 .csv 和 .xlsx 文件之间的区别)。

只需删除 .strftime('%m/%d/%Y') 就可以了。

【讨论】:

    猜你喜欢
    • 2023-03-31
    • 2021-07-14
    • 1970-01-01
    • 1970-01-01
    • 2015-01-20
    • 2021-09-09
    • 2017-03-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多