pandas 使用pandas.to_csv到YYYY-MM-DD时如何指定日期格式?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30245891/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 23:20:50  来源:igfitidea点击:

How to specify date format when using pandas.to_csv to YYYY-MM-DD?

pythondatepandas

提问by NumenorForLife

The OP of this posthighlighted the lack of documentation for using the date_format argument in pandas. I would like to format the data into YYYY-MM-DD, not MM/DD/YYYY when using the to_csv command.

这篇文章的 OP强调了在Pandas中使用 date_format 参数的文档的缺乏。我想在使用 to_csv 命令时将数据格式化为 YYYY-MM-DD,而不是 MM/DD/YYYY。

I've tried: frame.to_csv(output_dir, index=False, encoding='utf-8', date_format='%Y-%m-%d')and it is not working, where frame is a DataFrame

我试过:frame.to_csv(output_dir, index=False, encoding='utf-8', date_format='%Y-%m-%d')它不工作,其中 frame 是一个 DataFrame

The file I'm trying to convert can be found here

可以在此处找到我要转换的文件

回答by EdChum

This is already supported in to_csvas a param date_format:

这已经to_csv作为 param支持date_format

t="""date,val
12/05/1984,sadas
1/11/1980,sadas
2/4/1945,sadas
22/10/1921,sadas"""
df = pd.read_csv(io.StringIO(t), parse_dates=[0])
df.to_csv(r'c:\data\date.csv', date_format='%Y-%m-%d')

Yields:

产量:

,date,val
0,1984-12-05,sadas
1,1980-01-11,sadas
2,1945-02-04,sadas
3,1921-10-22,sadas

The format strings are of the form taken from strftime

格式字符串的格式取自 strftime

回答by Nicholas Aldershof

You can use the standard datetime string formatting behavior, here that would be: df.to_csv('df.csv, date_format="%Y-%m-%d") https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior

您可以使用标准的日期时间字符串格式化行为,这里是: df.to_csv('df.csv, date_format="%Y-%m-%d") https://docs.python.org/2/library /datetime.html#strftime-strptime-behavior

EDIT: don't iterate through the dataframe with strftime, that's highly unoptimized and theres already a built-in function for performing the operation you want

编辑:不要使用 strftime 遍历数据帧,这是高度未优化的,并且已经有一个内置函数来执行您想要的操作

回答by Gocht

You show iterate csv' rows and get every dateand format it with strptime method from datetime.

您显示迭代 csv' 行并获取每个日期并使用 datetime 中的 strptime 方法对其进行格式化。