Skip to content Skip to sidebar Skip to footer

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 a

Solution 1:

Try this:

import datetime
import pandas as pd 


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

Update: Edited as suggested by Josh.

Solution 2:

consider the df

today = pd.datetime.today().date()
begin = today - pd.offsets.Day(90)
tidx = pd.date_range(begin, today)
df = pd.DataFrame(dict(A=np.arange(len(tidx))), tidx)

you can slice the last 30 days like this

cut_off=today-pd.offsets.Day(29)df[cut_off:]A2016-09-23  612016-09-24  622016-09-25  632016-09-26  642016-09-27  652016-09-28  662016-09-29  672016-09-30  682016-10-01  692016-10-02  702016-10-03  712016-10-04  722016-10-05  732016-10-06  742016-10-07  752016-10-08  762016-10-09  772016-10-10  782016-10-11  792016-10-12  802016-10-13  812016-10-14  822016-10-15  832016-10-16  842016-10-17  852016-10-18  862016-10-19  872016-10-20  882016-10-21  892016-10-22  90

Post a Comment for "Filter Pandas Dataframe For Past X Days"