简体   繁体   中英

Errors while converting dataframe to csv

For an automation, I need to convert an excel file to csv along with some modifications in some columns. In one of the column I need to change the time stamp to %Y-%m-%d %H:%M:%S'. Currently I am able to do everything and the change reflects on the dataframe except that when I convert it to csv, the timestamp format changes,

This is the code I have been trying now

df=pd.read_excel(file,headers=0,index=False)
print(df.head())
df['Reported On '] = pd.to_datetime(df['Reported On '])
df['Reported On ']= df['Reported On '].apply(lambda x: dt.datetime.strftime(x, '%Y-%m-%d %H:%M:%S'))
df.to_csv(csv_name,index=False)

The Reported On column in CSV gives the value :8/10/2017 10:50

While if I convert the dataframe to excel, it gives me the required format.

Is it the problem of csv ?

Even if I can not reproduce your error, please note that you can define the string representation of dates in a csv-file at the time of writing the file instead of altering your data:

df=pd.read_excel(file,headers=0,index=False)
print(df.head())
df['Reported On '] = pd.to_datetime(df['Reported On '])
df.to_csv(csv_name, date_format='%Y-%m-%d %H:%M:%S', index=False)

This is IMO better anyway, because it leaves your dataframe independent from some output format requirements in a computable state.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM