I want to be able to sort my dataframe by ascending order of datetime but the format I have doesn't allow it to currently.

I have tried

df2['Date'] = pd.to_datetime(df2['Times'], format='%m/%d/%Y')

df2['Times'] = pd.to_datetime(df2['Times'], format='%H:%M:%S %p')

I currently have this

df2.iloc[:,0:2]


         Date     Times
0    1/2/2018   3:00 AM
1   10/3/2018   3:50 PM
2  10/10/2019  11:14 PM

and this is my desired output

         Date  Times
0  01/02/2018  03:00
1  10/03/2018  15:50
2  10/10/2019  23:14

or any output that will make it possible for me to sort by datetime.

1 Answers

0
jezrael On Best Solutions

You are close, main problem was use %I for match hour in 12h format and last use %H for hour in 24h format, check http://strftime.org/. Last add Series.dt.strftime for custom output format:

print (df2)
         Date     Times
0    1/2/2018   3:00 AM
1   10/3/2018   3:50 PM
2  10/10/2019  11:14 PM

df2['Date'] = pd.to_datetime(df2['Date'], format='%m/%d/%Y').dt.strftime('%m/%d/%Y')
df2['Times'] = (pd.to_datetime(df2['Times'].str.strip(), format='%I:%M %p')
                  .dt.strftime('%H:%M'))

print (df2)
         Date  Times
0  01/02/2018  03:00
1  10/03/2018  15:50
2  10/10/2019  23:14