How to get data in pandas dataframe in a range of date

866 views Asked by At

I have a front end where my clients select a date period like date_start = 2020/01/03 date_end = 2020/03/10

I have a data frame that has 1975 lines and 4 columns, including Date, like:

Date|Tax|Values|Total

I need to get all columns in that to be in a period between date_start and date_end on Pandas Dataframe. How Can I get it?

What I tried:

Try to do it with code:

new_df= df[(df['Date'] >= date_start) & (df['Date'] <= date_end)]

But the return was wrong.

2

There are 2 answers

8
Gorlomi On BEST ANSWER

welcome.

Keep in mind you're not filtering for those dates but selecting the dates in between.

Try the following:

# To make sure your column is in datetime format
df['Date'] = pd.to_datetime(df['Date'])  

new_df = df.loc[(df['Date']>=date_start) & (df['Date']<=date_end)]
0
Chasing Unicorn - Anshu On

Example:

from_date = "2021-08-27"
to_date = "2021-08-31"

inclusive can be {“both”, “neither”, “left”, “right”}

df[df['date'].between(from_date, to_date, inclusive='both')]

This function is equivalent to:

 df[(from_date <= df['date']) & (df['date'] <= to_date)]