Question: I am trying to change the format of the date in a pandas dataframe. 
If I check the date in the beginning, I have:

```
df['Date'][0]
Out[158]: '01/02/2008'

```

Then, I use:

```
df['Date'] = pd.to_datetime(df['Date']).dt.date  

```

To change the format to 

```
df['Date'][0]
Out[157]: datetime.date(2008, 1, 2)

```

However, this takes a veeeery long time, since my dataframe has millions of rows. 

All I want to do is change the date format from MM-DD-YYYY to YYYY-MM-DD.
How can I do it in a faster way?

Answer: 
You should first collapse by `Date` using the `groupby` method to reduce the dimensionality of the problem.

Then you parse the dates into the new format and merge the results back into the original DataFrame.

This requires some time because of the merging, but it takes advantage from the fact that many dates are repeated a large number of times. You want to convert each date only once!

You can use the following code:

```
date_parser = lambda x: pd.datetime.strptime(str(x), '%m/%d/%Y')

df['date_index'] = df['Date']
dates = df.groupby(['date_index']).first()['Date'].apply(date_parser)

df = df.set_index([ 'date_index' ])
df['New Date'] = dates
df = df.reset_index()

df.head()

```

In my case, the execution time for a DataFrame with 3 million lines reduced from 30 seconds to about 1.5 seconds.
Following a lead at @pygo's comment, I found that my mistake was to try to read the data as

```
df['Date'] = pd.to_datetime(df['Date']).dt.date  

```

This would be, as [this answer](https://stackoverflow.com/questions/32034689/why-is-pandas-to-datetime-slow-for-non-standard-time-format-such-as-2014-12-31) explains:

> 
> This is because pandas falls back to dateutil.parser.parse for parsing the strings when it has a non-default format or when no format string is supplied (this is much more flexible, but also slower).
> 
> 
> As you have shown above, you can improve the performance by supplying a format string to to\_datetime. Or another option is to use infer\_datetime\_format=True
> 
> 
> 

When using any of the date parsers from the answers above, we go into the for loop. Also, when specifying the format we want (instead of the format we have) in the pd.to\_datetime, we also go into the for loop.

Hence, instead of doing

```
df['Date'] = pd.to_datetime(df['Date'],format='%Y-%m-%d')

```

or

```
df['Date'] = pd.to_datetime(df['Date']).dt.date  

```

we should do

```
df['Date'] = pd.to_datetime(df['Date'],format='%m/%d/%Y').dt.date

```

By supplying the current format of the data, it is read really fast into datetime format. Then, using .dt.date, it is fast to change it to the new format without the parser.

Thank you to everyone who helped!