Python 使用pandas.to_csv时如何指定日期格式?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13999850/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to specify date format when using pandas.to_csv?
提问by
The default output format of to_csv()is:
的默认输出格式to_csv()为:
12/14/2012 12:00:00 AM
I cannot figure out how to output only the date part with specific format:
我无法弄清楚如何仅输出具有特定格式的日期部分:
20121214
or date and time in two separate columns in the csv file:
或 csv 文件中两个单独列中的日期和时间:
20121214, 084530
The documentation is too brief to give me any clue as to how to do these. Can anyone help?
文档太简短了,无法给我任何关于如何执行这些操作的线索。任何人都可以帮忙吗?
采纳答案by Andy Hayden
You could use strftimeto save these as separate columns:
您可以使用strftime将这些保存为单独的列:
df['date'] = df['datetime'].apply(lambda x: x.strftime('%d%m%Y'))
df['time'] = df['datetime'].apply(lambda x: x.strftime('%H%M%S'))
and then be specific about which columns to export to csv:
然后具体说明要导出到 csv 的列:
df[['date', 'time', ... ]].to_csv('df.csv')
回答by BubbleGuppies
Since version v0.13.0 (January 3, 2014)of Pandas you can use the date_formatparameter of the to_csvmethod:
从Pandas 的 v0.13.0(2014 年 1 月 3 日)版本开始,您可以使用to_csv方法的date_format参数:
df.to_csv(filename, date_format='%Y%m%d')
回答by Benjamin Crouzier
To export as a timestamp, do this:
要导出为时间戳,请执行以下操作:
df.to_csv(filename, date_format='%s')
The %sformat is not documented in python/pandasbut works in this case.
该%s格式未记录在 python/pandas 中,但在这种情况下有效。
I found the %sfrom the dates formats of ruby. Strftime doc for C here
我%s从ruby 的日期格式中找到了。此处为 C 的 Strftime 文档
Note that the timestamp miliseconds format %Qdoes not work with pandas (you'll have a litteral %Qin the field instead of the date). I caried my sets with python 3.6 and pandas 0.24.1
请注意,时间戳毫秒格式%Q不适用于熊猫(您将%Q在字段中使用文字而不是日期)。我用 python 3.6 和 pandas 0.24.1 处理了我的集合

