Home > Enterprise >  Pandas Sorting by datetime
Pandas Sorting by datetime

Time:11-04

I have a pandas dataframe filled with time-stamped data. It is out of order; and I am trying to sort by date, hours and minutes. The pandas dataframe will organize by date, but not by hours and minutes.

My dataframe is loaded in ('df'), and the column 'dttime' was changed it into a dateframe from integer numbers.

df['dttime'] = pd.to_datetime(df['dttime'], format='%y%m%d%H%M%S')

I resort it with:

df.sort_values(by='dttime')    

but that does not seem to have the right ordering of the hour minutes and seconds.

CodePudding user response:

I tried with some dummy data and it doesn't look like an issue to me. Please check the below code.

import pandas as pd
data = ['221011141200', '221011031200', '221011191200', '221011131600']

df = pd.DataFrame(data, columns=['dttime'])
df['dttime'] = pd.to_datetime(df['dttime'], format='%y%m%d%H%M%S')

# Before sorting
print(df)

# After sorting
df = df.sort_values(by='dttime')
print(df)

Output is as follows:

               dttime
0 2022-10-11 14:12:00
1 2022-10-11 03:12:00
2 2022-10-11 19:12:00
3 2022-10-11 13:16:00

               dttime
1 2022-10-11 03:12:00
3 2022-10-11 13:16:00
0 2022-10-11 14:12:00
2 2022-10-11 19:12:00
  • Related