3

I have a dataframe with multiple columns

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']})

I want to export this df to a csv file using pandas' .to_csv(...) and save the column date in the format %Y-%m-%d but the column datetime in the format %Y-%m-%d %H:%M:%S and can't find a way to modify the code accordingly.

I have tried

  1. df.to_csv('output.csv', date_format = '%Y-%m-%d'), which transforms all columns' date format, including the column datetime, where I want to keep the time.
  2. df.to_csv('output.csv') (without using date_format = ...) displays all columns' date format as datetime - yet I want the column date to not carry the time-component.

Does anyone have an idea of how to do this? Thanks a ton in advance.

1 Answer 1

1

I think selective is not possible, docs:

date_format: Format string for datetime objects

Solution is convert column to dates before to_csv:

df['date'] = df['date'].dt.date
print (df.to_csv())

Or:

print (df.assign(date=df['date'].dt.date).to_csv())

,date,text,datetime
0,2011-01-01,red,2011-01-01 10:15:20
1,2016-11-17,purple,2016-11-17 08:22:10
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.