[英]How to specify date format when using pandas.to_csv to YYYY-MM-DD?
The OP of this post highlighted the lack of documentation for using the date_format argument in pandas. 这篇文章的OP强调了在pandas中使用date_format参数缺乏文档。 I would like to format the data into YYYY-MM-DD, not MM/DD/YYYY when using the to_csv command. 我想在使用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 我正在尝试转换的文件可以在这里找到
This is already supported in to_csv
as 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
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迭代数据帧,这是非常不优化的,并且已经有一个内置函数来执行你想要的操作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.