Filter By Dates In Python Pandas

Posted August 16, 2022 by Rohith ‐ 1 min read

In python pandas, filtering data by dates can be achieved by first casting the data to datetime and apply range of dates to the python datatframe.

TL;DR

  1. Convert the column to datetime dtype using to_datetime()
  2. apply filters on the datetime dtype column

Example:

df['dt_column'] = pd.to_datetime(df['dt_column'])
df = df[
          (df['dt_column'] > '2022-07-24 05:30:00') & 
          (df['dt_column'] < '2022-08-03 10:00:00')
        ]

So long as dt_column is a datetime dtype already you can straight filter using date strings, if the column is not in datetime dtype then we have to convert to the datetime datype.

Convert the DataFrame Column To datetme

A python dataframe column can be converted to datetime dtype using to_datetime pandas method.

Example:

import pandas as pd

df['dt_column'] = pd.to_datetime(df['dt_column'])

Filter Pandas Data By Dates

Use & operator for filtering between the dates. And use >, >=, <= and < operators to filter.

Example:


df = df[
          (df['dt_column'] >= '2022-08-01 00:00:00') & 
          (df['dt_column'] < '2022-09-01 00:00:00')
        ]
python pandas filter datetime

Subscribe For More Content