Josh Josh - 1 month ago 7
Python Question

filter pandas dataframe for past x days

I have a dataframe with a date column that I update daily. I'd like to create a copy of it with just the past 30 day's of data.

I tried the following syntax based on what I know about doing this in R:

df[df[date]>dt.date.today()-30]


The date column is not the index but I'm not opposed to making it so if that helps!

Thanks!

Answer

Try this:

import datetime
import pandas as pd 


df[df.the_date_column.dt.date > datetime.datetime.now() - pd.to_timedelta("30day")]