首页 > 解决方案 > ExcelWriter ValueError:将 df 保存到 Excel 时,Excel 不支持带时区的日期时间

问题描述

我在这个问题上运行了很长一段时间。

我将编写器设置如下:

writer = pd.ExcelWriter(arquivo+'.xlsx', engine = 'xlsxwriter', options = {'remove_timezone': True})
df.to_excel(writer, header = True, index = True)

这段代码在 s 函数中。问题是每次我运行代码时,它都会从数据库中获取信息,其中包含两列 datetime64[ns, UTC] 对象和时区信息。但是当保存到 Excel 的代码运行时,我收到:

ValueError: Excel does not support datetimes with timezones. Please ensure that datetimes are timezone unaware before writing to Excel.

我已经尝试了几种方法,例如 'dt.tz_convert'、replace(tzinfo=None) 以及我在这里和周围找到的其他解决方案。

代码在我的个人计算机上运行没有问题,我的同事使用相同的机器规格可以运行代码。只有在我的机器上没有。我已经重新安装了python和所有的包,包括格式化机器什么都没有,错误仍然存​​在。

xlrd v1.1.0

xlsxwriter v1.0.4

蟒蛇 3.7.4

熊猫 v0.25.1

如果有人可以为这个问题带来一些启发,我将不胜感激。

谢谢

标签: pythonpandasxlsxwriter

解决方案


你的时间戳是什么格式的?

我只是有一个类似的问题。

我试图将数据框保存到 Excel。但是我得到了:

错误代码

我检查了我的日期格式,它是这种格式'2019-09-01T00:00:00.000Z'

这是pandas._libs.tslibs.timestamps.Timestamp 来自的时间戳pandas.to_datetime

其中包括date()将日期转换为"%Y-%m-%d"excel 可接受的格式的方法

所以我的代码是这样的:

#Pseudo
df['date'] = old_dates
df['date'] = df['date'].apply(lambda a: pd.to_datetime(a).date()) 
# .date() removes timezone

...df.to_excel etc.

推荐阅读