Danish
Danish

Reputation: 2871

Filter data frame based on date columns pandas

I have a pandas data frame as shown below.

Unit_ID    Added_Date                   Status         
105        2019-10-02 07:18:18          Rented
106        2020-15-01 07:18:17          Rented
105        2019-10-02 07:18:19          Rented
108        2020-15-01 07:18:18          Vacant

From the above I would like to find out the Unit_ID which has been added within last 10 days based on the Date column.

Expected Output:

Unit_ID    Added_Date                   Status         
106        2020-15-01 07:18:17          Rented
108        2020-15-01 07:18:18          Vacant

Upvotes: 2

Views: 57

Answers (3)

Umar.H
Umar.H

Reputation: 23099

Here's another way using pd.DateOffset

from datetime import datetime
df.loc[df['Added_Date'] >= (datetime.today() - pd.DateOffset(days=10))]

   Unit_ID          Added_Date  Status
1      106 2020-01-15 07:18:17  Rented
3      108 2020-01-15 07:18:18  Vacant

Upvotes: 2

anky
anky

Reputation: 75080

you can also use the .dt.days accessor and compare with le 10:

#df['Added_Date']=pd.to_datetime(df['Added_Date'],format='%Y-%d-%m %H:%M:%S')
df[(pd.to_datetime('today') - df['Added_Date'] ).dt.days.le(10)]

   Unit_ID          Added_Date  Status
1      106 2020-01-15 07:18:17  Rented
3      108 2020-01-15 07:18:18  Vacant

Upvotes: 3

YOLO
YOLO

Reputation: 21709

Here's a way to do:

today = pd.to_datetime('today')
n = 10 # last n days

filter_criteria = df['Added_Date'].sub(today).abs().apply(lambda x: x.days <= n)

df.loc[filter_criteria]

     Unit_ID Added_Date           Status
106      106 2020-01-15 07:18:17  Rented
108      108 2020-01-15 07:18:18  Vacant

Upvotes: 2

Related Questions