英文:
Writing Datetime to excel with pandas
问题
I'm trying to export my Data table to excel. It consist of 16 columns where 2 are date time.
我想将我的数据表导出到Excel,其中包含16列,其中有2列是日期时间。
I was able to convert datetime to date and save the file without getting this error message:
我成功将日期时间转换为日期并保存文件,没有收到此错误消息:
ValueError: time data '2023-04-07 13:06:18.931000+00:00' does not match format 'DD-MMM-YYYY HH:MM:SS' (match).
ValueError: 时间数据 '2023-04-07 13:06:18.931000+00:00' 与格式 'DD-MMM-YYYY HH:MM:SS' 不匹配。
If I change the format to DD-MM-YYYY HH:MM:SS then that error appears:
如果我将格式更改为DD-MM-YYYY HH:MM:SS,然后出现该错误:
ValueError: Excel does not support datetimes with timezones. Please ensure that datetimes are timezone unaware before writing to Excel.
ValueError: Excel不支持带有时区的日期时间。请确保在写入Excel之前日期时间是无时区的。
df2 = pd.DataFrame.from_dict(dicts)#assign the data to pandas
#change datetime to excel format. Excel don't have datetime
#将日期时间更改为Excel格式。Excel不支持日期时间
df2['Creation date'] = pd.to_datetime(df2['Creation date'], format="DD-MMM-YYYY HH:MM:SS", utc=True)
df2['Updated date'] = pd.to_datetime(df2['Updated date'], format="DD-MMM-YYYY HH:MM:SS", utc=True)
df2 = pd.DataFrame.from_dict(dicts)#将数据分配给pandas
#将日期时间更改为Excel格式。Excel不支持日期时间
df2['Creation date'] = pd.to_datetime(df2['Creation date'], format="DD-MMM-YYYY HH:MM:SS", utc=True)
df2['Updated date'] = pd.to_datetime(df2['Updated date'], format="DD-MMM-YYYY HH:MM:SS", utc=True)
How can I convert it and keep to desired format and avoid timezone error?
如何转换它并保持所需的格式,避免时区错误?
英文:
I'm trying to export my Data table to excel. It consist of 16 columns where 2 are date time.
I was able to convert datetime to date and save the file without getting this error message:
ValueError: time data '2023-04-07 13:06:18.931000+00:00' does not match format 'DD-MMM-YYYY HH:MM:SS' (match).
If I change the format to DD-MM-YYYY HH:MM:SS then that error appears:
ValueError: Excel does not support datetimes with timezones. Please ensure that datetimes are timezone unaware before writing to Excel.
df2 = pd.DataFrame.from_dict(dicts)#assign the data to pandas
#change datetime to excel format. Excel don't have datetime
df2['Creation date'] = pd.to_datetime(df2['Creation date'],format="DD-MMM-YYYY HH:MM:SS",utc=True)
df2['Updated date'] = pd.to_datetime(df2['Updated date'],format="DD-MMM-YYYY HH:MM:SS",utc=True)
How can I convert it and keep to desired format and avoid timezone error?
答案1
得分: 0
将其转换为字符串并避免日期和时区等问题:
df2['Creation date'] = df2['Creation date'].dt.strftime('%Y-%m-%d %H:%M:%S')
df2['Updated date'] = df2['Updated date'].dt.strftime('%Y-%m-%d %H:%M:%S')
英文:
Ok decided to conver it into str and avoid any problems with date and time zones etc.
df2['Creation date'] = df2['Creation date'].dt.strftime('%Y-%m-%d %H:%M:%S')
df2['Updated date'] = df2['Updated date'].dt.strftime('%Y-%m-%d %H:%M:%S')
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论