Home > database >  Select the dataframe based on the certain time value in pandas
Select the dataframe based on the certain time value in pandas

Time:01-05

I have a dataframe

df = pd.DataFrame([["A","11:40 AM"],["B","12:51 PM"],["C","6:33 PM"],["D","11:13 AM"],["E","7:13 PM"]],columns=["id","time"])
id    time
A   11:40 AM
B   12:51 PM
C    6:33 PM
D   11:13 AM
E    7:13 PM

I want to select only those rows which are < 6:30 PM.

Expected output:

df = pd.DataFrame([["A","11:40 AM"],["B","12:51 PM"],["D","11:13 AM"]],columns=["id","time"])
id    time
A   11:40 AM
B   12:51 PM
D   11:13 AM

I tried df[(df['time'].dt.time < '18:30:00')]. It is giving an error. How to do it?

CodePudding user response:

Try converting to datetime first:

df.loc[pd.to_datetime(df['time']).le(pd.Timestamp('18:30:00'))]

Output:

  id      time
0  A  11:40 AM
1  B  12:51 PM
3  D  11:13 AM
  • Related