Jonathan Stearns
Jonathan Stearns

Reputation: 314

Filter a list of dates - keep dates that only are multiple of 5 minutes

I have a dataframe. One of the columns is a DateTime Object. I want to filter the entire dataframe and leave only the rows where the DateTimes are multiple of 5's.

Example dates from the column:

6/25/2021 9:48
6/25/2021 9:49
6/25/2021 9:50
6/25/2021 9:51
6/25/2021 9:52
6/25/2021 9:54
6/25/2021 9:56
6/25/2021 9:59
6/25/2021 10:01
6/25/2021 10:02
6/25/2021 10:03
6/25/2021 10:04
6/25/2021 10:05
6/25/2021 10:06
6/25/2021 10:07
6/25/2021 10:08
6/25/2021 10:09
6/25/2021 10:10
6/25/2021 10:11
6/25/2021 10:12
6/25/2021 10:13
6/25/2021 10:14
6/25/2021 10:15

Desired Output:

6/25/2021 9:50
6/25/2021 9:55
6/25/2021 10:00
6/25/2021 10:05
6/25/2021 10:10
6/25/2021 10:15

Upvotes: 0

Views: 505

Answers (1)

Pavan Suvarna
Pavan Suvarna

Reputation: 501

you can use pandas.to_datetime to convert a series to DateTime object and then access the minute value and use modulo(%) operator.

import pandas as pd
df['date'] = pd.to_datetime(df['date'])
df['filter'] = [i.minute % 5 for i in df['date']]
df = df[df['filter'] == 0]
#df.drop(columns = ['filter'], inplace= True) -- drop extra column

and if you do not want to alter the date column, just use

df['filter'] = [i.minute % 5 for i in pd.to_datetime(df['date'])]
df = df[df['filter'] == 0]

Upvotes: 1

Related Questions