Home > Software engineering >  Lost the second of the datetime when exporting to the CSV file?
Lost the second of the datetime when exporting to the CSV file?

Time:02-24

It will lost the second when exporting to the csv file? why? "%S" is none?

df = pd.DataFrame({'date': ['2011-01-01 10:15:20', '2016-11-17 08:22:10'],
'text': ['red', 'purple'],'datetime': ['2011-01-01 10:15:20', '2016-11-17 08:22:10']})
df.to_csv("test.csv",date_format="%Y-%m-%d %H:%M:%S")

In the csv file ,it is:

    date    text    datetime
0   2011/1/1 10:15  red 2011/1/1 10:15
1   2016/11/17 8:22 purple  2016/11/17 8:22

CodePudding user response:

If you open the file in the Excel Application, the seconds would be truncated based on the default format. I would recommend to open the file in text editors like - Notepad , Sublime where the format is preserved.

I ran the below code as it is,

df = pd.DataFrame({'date': ['2011-01-01 10:15:20', '2016-11-17 08:22:10'],
'text': ['red', 'purple'],'datetime': ['2011-01-01 10:15:20', '2016-11-17 08:22:10']})
df.to_csv("test.csv",date_format="%Y-%m-%d %H:%M:%S")

Below is the output I got when opened in Notepad

enter image description here

  • Related