Python Forum

Full Version: how to retain time format in df.to_csv
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,
I have below data in csv file, and I read the file and rewrite. When write to csv using df.to_csv, it lossing time format, I want to show full time format (yyyy/mm/dd hh:mm:ss). How to define the time formart.

The time in csv file showing (when open) in the form: mm:ss.0, but when I click on particular cell the time format is
mm:ss.o

Name	Age	  date_in	        date_out
A	   23	  2020/08/07 20:12	2020/08/07 20:45
B	   28	  2020/08/11 20:12	2020/08/11 20:42
but it showing (unless I click on cell to see full time format)

Name   Age	    date_in	  date_out
A	   23	    20:12	  20:45
B	   28	    20:12	  20:42
But I want to write in to file an dshow it in fie whne open:

Name	Age	  date_in	        date_out
A	   23	  2020/08/07 20:12	2020/08/07 20:45
B	   28	  2020/08/11 20:12	2020/08/11 20:42
I use below code:

import pandas as pd
df = pd.read_csv(r'PythonCodes\timeForm2.csv')
df.dropna(how='any',inplace=True)
df.to_csv('timeFormOut2.csv',index=False)
You need to define date_format parameter in .to_csv method. See docs to construct an appropriate format string.
because you speak of click on cell - note that csv format has no concept of cell. It's plain text file. I guess you just view the csv file in Excel/some spreadsheets program. To see what you really have in your file - open the csv file in editor like notepad or notepad++. Presentation in excel may be affected by many factors