Filtering Pandas Dataframe on Time (not Date)

I have the dataframe below and want to filter by time. The time column comes up as an object when I use dtypes.

To get the time to use as the filter criteria I use split:

start_time = "25 September 2022, 13:00:00"
split_time = start_time.split(", ")[1]

I have tried converting split_time and the df column to datime but get an error on the df column conversion:

TypeError: <class ‘datetime.time’> is not convertible to datetime

I have also tried a simple string search but this doesn’t return any results.

I have been able to filter by date using:

split_date = start_time.split(", ")[0]
event_date = datetime.strptime(split_date, "%d %B %Y") 
events_df['start_date'] = pd.to_datetime(events_df['start_date']) 
filtered_df = events_df.loc[(events_df['start_date'] == event_date)]

But can’t seem to do the equivalent for time. Can anyone see the problem?


fixture_id name start_date time
145 9394134 Plymouth Argyle v Ipswich Town 2022-09-25 00:00:00 12:30:00
146 9694948 Grays Athletic v Merstham FC 2022-09-25 00:00:00 13:00:00
147 9694959 FC Romania v Faversham Town 2022-09-25 00:00:00 15:00:00

>Solution :

Comapre times generated by Series.dt.time with Timestamp.time:

start_time = "25 September 2022, 13:00:00"
dt = pd.to_datetime(start_time, format="%d %B %Y, %H:%M:%S")

events_df['start_date'] = pd.to_datetime(events_df['start_date'])
#if necessary
events_df['time'] = pd.to_datetime(events_df['time']).dt.time

filtered_df = events_df.loc[(events_df['time'] == dt.time())]
print (filtered_df)
        fixture_id                          name start_date      time
1  146     9694948  Grays Athletic v Merstham FC 2022-09-25  13:00:00

Leave a Reply