[英]How to specify date format when using pandas.to_csv?
The default output format of to_csv()
is: to_csv()
的默认 output 格式为:
12/14/2012 12:00:00 AM
I cannot figure out how to output only the date part with specific format:我无法弄清楚如何 output 仅具有特定格式的日期部分:
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?任何人都可以帮忙吗?
从Pandas 的 v0.13.0(2014 年 1 月 3 日)版本开始,您可以使用to_csv方法的date_format
参数:
df.to_csv(filename, date_format='%Y%m%d')
You could use strftime
to 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')
To export as a timestamp, do this:要导出为时间戳,请执行以下操作:
df.to_csv(filename, date_format='%s')
The %s
format is not documented in python/pandas but works in this case. %s
格式未记录在 python/pandas 中,但在这种情况下有效。
I found the %s
from the dates formats of ruby .我从ruby 的日期格式中找到了%s
。 Strftime doc for C here此处为 C 的 Strftime 文档
Note that the timestamp miliseconds format %Q
does not work with pandas (you'll have a litteral %Q
in the field instead of the date).请注意,时间戳毫秒格式%Q
不适用于大熊猫(您将在字段中使用文字%Q
而不是日期)。 I caried my sets with python 3.6 and pandas 0.24.1我用 python 3.6 和 pandas 0.24.1 处理了我的集合
Non of these timestamp formats seem to work for me.这些时间戳格式似乎都不适合我。
Tried:试过:
from datetime import datetime
ordersUnleashed.to_csv('sendtoUnleashed.csv', date_format='%s.%f')
And from https://lifewithdata.com/2021/12/10/pandas-to_csv-write-a-dataframe-to-a-csv-file/#specifying-datetime-format-when-saving-a-csv-file从https://lifewithdata.com/2021/12/10/pandas-to_csv-write-a-dataframe-to-a-csv-file/#specifying-datetime-format-when-saving-a-csv-file
No luck.没运气。 Even tried pip install datetime.甚至尝试过 pip 安装日期时间。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.