Python pandas数据框“日期"在xlsx和csv中索引不同的格式 [英] Python pandas dataframe "Date" Index different format in xlsx and csv

查看:119
本文介绍了Python pandas数据框“日期"在xlsx和csv中索引不同的格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有多个标签的xlsx文件,每个标签都有一个Date列,格式为MM/DD/YYYY

I have an xlsx file with multiple tabs, each tab has a Date column in the format of MM/DD/YYYY

将每个选项卡读入pandas数据框,对每个选项卡进行一些操作,然后将数据框写回两种格式:xlsx和csv

Read each tab into a pandas dataframe, applied some operations on each tab, and then write the dataframe back into two formats: xlsx and csv

在xlsx文件中,Date列(索引)变成具有附加时间的格式:1/1/2013 12:00:00 AM,而csv文件中的Date列保持不变:MM/DD/YYYY

In the xlsx file, the Date column (index) becomes a format that has the time attached: 1/1/2013 12:00:00 AM, while the Date column in the csv file remains unchanged: MM/DD/YYYY

如何确保xlsx文件中的Date列保持相同的格式MM/DD/YYYY?

How can I make sure the Date column in the xlsx file maintains the same format MM/DD/YYYY?

推荐答案

您看到的是默认熊猫Excel日期时间格式的日期时间.但是,您可以轻松地将其设置为所需的任何内容:

You are seeing the datetime in the default pandas Excel datetime format. However, you can easily set it to whatever you want:

# Set the default datetime and/or date formats.
writer = pd.ExcelWriter("pandas_datetime.xlsx",
                        engine='xlsxwriter',
                        date_format='mm/dd/yyy',
                        datetime_format='mm/dd/yyyy')

# Convert the dataframe to an XlsxWriter Excel object.
df.to_excel(writer, sheet_name='Sheet1')

在XlsxWriter文档中查看完整的示例:示例:带有日期时间的熊猫Excel输出.

See a full example in the XlsxWriter docs: Example: Pandas Excel output with date times.

这篇关于Python pandas数据框“日期"在xlsx和csv中索引不同的格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆