pandas 保存到csv文件python时日期时间格式更改
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30298144/
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
datetime format change when save to csv file python
提问by markov zain
I have a dataframe like this:
我有一个这样的数据框:
In [67]:
call_df.head()
Out[67]:
timestamp types
1 2014-06-30 07:00:55 Call_O
2 2014-06-30 07:00:05 Call_O
3 2014-06-30 06:54:55 Call_O
501 2014-06-30 11:24:01 Call_O
When I saved that dataframe to csv file, the format of datetime is change as well as I lose the seconds. I just put this code to save into csv file:
当我将该数据帧保存到 csv 文件时,日期时间的格式会发生变化并且我丢失了秒数。我只是把这段代码保存到 csv 文件中:
call_df.to_csv('D:/Call.csv')
The csv file output is like this:
csv文件输出是这样的:


In here I want to ask, how to save the same datetime format from dataframe into csv file
在这里我想问一下,如何将相同的日期时间格式从数据帧保存到 csv 文件中
回答by EdChum
to_csvaccepts a date_formatparam, so please try this:
to_csv接受一个date_format参数,所以请试试这个:
call_df.to_csv('D:/Call.csv', date_format='%Y-%m-%d %H:%M:%S')
On your sample data set this yielded:
在您的样本数据集上,这产生了:
timestamp,types
2014-06-30 07:00:55,Call_O
2014-06-30 07:00:05,Call_O
2014-06-30 06:54:55,Call_O
2014-06-30 11:24:01,Call_O
回答by Gurtej Khanooja
The answer to this problem is a two-step process:
这个问题的答案是一个两步过程:
1) Convert the timestamp column to date time first:
1)先将时间戳列转换为日期时间:
call_df['timestamp'] = call_df['timestamp'].astype('datetime64[ns]')
2) Add date_format argument while using the "to_csv" after performing the first step:
2) 执行第一步后,在使用“to_csv”时添加 date_format 参数:
call_df.to_csv("Call.csv", date_format='%Y-%m-%d %H:%M:%S')
回答by sachin saxena
Change your datetime columns to string by :
通过以下方式将日期时间列更改为字符串:
call_df['timestamp'] = call_df['timestamp'].apply(lambda v: str(v))
then you can save to csv to retain the format
然后您可以保存到 csv 以保留格式
回答by Chetchaiyan
You problem isn't a python problem and it can't be fix directly. Why?
你的问题不是 python 问题,它不能直接修复。为什么?
when you open csv file from excel, it will convert your data to any type it should be in this case your data converted to date type then excel apply default date format to that data. Also, you can't control the date format of excel file since csv files is only a text file, no meta or hidden data to advise excel to proceed.
当您从 excel 打开 csv 文件时,它会将您的数据转换为任何类型,在这种情况下,您的数据应该转换为日期类型,然后 excel 将默认日期格式应用于该数据。此外,您无法控制 excel 文件的日期格式,因为 csv 文件只是一个文本文件,没有元数据或隐藏数据来建议 excel 继续。
If you still want to control your format in excel, you need to force your data to be string, not date. most of the case we add ' in front of any data we prefer string format. You will get the correct format display as you want but you lose your date data type.
如果你仍然想在 excel 中控制你的格式,你需要强制你的数据是字符串,而不是日期。大多数情况下,我们在任何我们喜欢字符串格式的数据前添加 '。您将根据需要获得正确的格式显示,但您会丢失日期数据类型。

