10

I have this panda dataframe df.

Name      Date      Score  Score2
Joe     26-12-2007  53.45  53.4500
Joe     27-12-2007  52.38  52.7399
Joe     28-12-2007  51.71  51.8500

I would like to convert the date format in the Date column from dd-mm-yyyy to yyyy-mm-dd. The converted dataframe will look like this;

Name      Date      Score  Score2
Joe     2007-12-26  53.45  53.4500
Joe     2007-12-27  52.38  52.7399
Joe     2007-12-28  51.71  51.8500

I am using python v3.6

A question marked as duplicate assumes that the original date format is yyyy-mm-dd. However, the original date format in this question is dd-mm-yyyy. If I were to apply the answer in that question, the converted dates is wrong. How to change the datetime format in pandas

user1315789
  • 3,069
  • 6
  • 18
  • 41
  • Usually you only want to change the display format used to display the datetime, per [How to change the datetime format in pandas](https://stackoverflow.com/questions/38067704/how-to-change-the-datetime-format-in-pandas). **You don't want to modify the underlying data. In particular you don't want to convert to string with `.strftime('new_format')` then convert back with `pd.to_datetime`**. Why? There are multiple pitfalls in doing that (some dates might not comply with the new format, throw exceptions, mixed formats, mixed or missing timezones, etc.) – smci Apr 20 '20 at 08:37

1 Answers1

26

Use '%Y-%m-%d'

Ex:

import pandas as pd

df = pd.DataFrame({"Date": ["26-12-2007", "27-12-2007", "28-12-2007"]})
df["Date"] = pd.to_datetime(df["Date"]).dt.strftime('%Y-%m-%d')
print(df)

Output:

         Date
0  2007-12-26
1  2007-12-27
2  2007-12-28
Rakesh
  • 81,458
  • 17
  • 76
  • 113