使用pandas.to_csv时如何指定日期格式?
问题描述:
to_csv()
的默认输出格式为:
12/14/2012 12:00:00 AM
我无法弄清楚如何仅输出具有特定格式的日期部分:
I cannot figure out how to output only the date part with specific format:
20121214
或csv文件中两个单独列中的日期和时间:
or date and time in two separate columns in the csv file:
20121214, 084530
文档太简短,无法给我任何有关如何执行这些操作的线索.有人可以帮忙吗?
The documentation is too brief to give me any clue as to how to do these. Can anyone help?
答
You could use strftime
to save these as separate columns:
df['date'] = df['datetime'].apply(lambda x: x.strftime('%d%m%Y'))
df['time'] = df['datetime'].apply(lambda x: x.strftime('%H%M%S'))
,然后具体说明要导出到csv的列:
and then be specific about which columns to export to csv:
df[['date', 'time', ... ]].to_csv('df.csv')