Home > Mobile >  Filter time in a dataframe using python
Filter time in a dataframe using python

Time:12-21

I have a column where there is only time. After reading that CSV file i have converted that column to datetime datatype as it was object when i read it in jupyter notebook. When i try to filter i am getting error like below

TypeError: Index must be DatetimeIndex

code

newdata = newdata['APPOINTMENT_TIME'].between_time('14:30:00', '20:00:00')

sample_data

APPOINTMENT_TIME Id
13:30:00    1
15:10:00    2
18:50:00    3
14:10:00    4
14:00:00    5

Here i am trying display the rows whose appointment_time is between 14:30:00 to 20:00:00 datatype info

Could anyone help. Thanks in advance

CodePudding user response:

between_time is a special method that works with datetime objects as index, which is not your case. It would be useful if you had data like 2021-12-21 13:30:00

In your case, you can just use the between method on strings and the fact that times with your format HH:MM:SS will be naturally sorted:

filtered_data = newdata[newdata['APPOINTMENT_TIME'].between('14:30:00', '20:00:00')]

Output:

  APPOINTMENT_TIME  Id
1         15:10:00   2
2         18:50:00   3

NB. You can't use a range that starts before midnight and ends after.

  • Related