用pandas书写excel表格的date错误

我使用pandas.DataFrame.to_excel()函数将一些从数据库加载的文件写入Excel电子表格。 正在使用的function如下:

def country_reports(countries): writer = pd.ExcelWriter('country_reports.xlsx') for country in countries: df = report(country) df.to_excel(writer, country) writer.save() 

report(country)方法只是返回该国家相关数据的DataFrame 。 我想为多个国家运行此报告,然后在Excel中将各个国家的数据显示在其自己的选项卡中。 这通常是非常简单的,但我有一些我的DataFrames,早于1900年的date,这使我不可能写入Excel,因为它会引发错误:

ValueError:Excel不支持的年份:1861。

在将这些文件编写为CSV时,我没有任何问题,所以我很好奇,是否有一些方法可以创build一个具有多个由CSV表示的选项卡的Excel文件? 如果没有,是否有另一种解决这个问题的方法?

你只需要在Excel中显示date? 如果是这样的话,你可以转换成一个string,就像这样。

 df['date_col'] = df['date_col'].apply(lambda x: x.date().isoformat()) 

如果您实际上需要在Excel中处理date,最好将每月/每天/每年分为不同的列,如下所示:

 df['year'] = df['date_col'].apply(lambda x: x.year) df['day'] = df['date_col'].apply(lambda x: x.day) df['month'] = df['date_col'].apply(lambda x: x.month)