Ad

Python - How To Sort Date String In A Data Frame?

- 1 answer

I have a df pandas.core.series.Series such that:

0        11/8/16
1        11/8/16
2        6/12/16
3       10/11/15
4       10/11/15
          ...   
9989     1/21/14
9990     2/26/17
9991     2/26/17
9992     2/26/17
9993     12/30/17

If I use max() on it, it shows the latest date as '9/9/17', instead of the actual maximum which is, in this case '12/30/17'.

I understand why it is happens - because 9 > 1.

How can I fix it?

Ad

Answer

Convert the dates to timestamps first:

import pandas as pd
df["date"] = pd.to_datetime(df["date"], format="%m/%d/%y")
>>> df["date"].max()
Ad
source: stackoverflow.com
Ad