Home > Enterprise >  How to retrieve only dataframe rows where column field values are exactly 7 days more than current t
How to retrieve only dataframe rows where column field values are exactly 7 days more than current t

Time:03-31

I am trying to retrieve specific rows from the pandas data frame where the date of the column is exactly 7 days more than the current time. For example, current date is 2022-03-22. Here is my dataframe:

        name      date              

0       Max     2022-03-24

1       Joe     2022-03-29

2       Moe     2022-04-03

Now I want to retrieve ONLY Joe since he has the date exactly 7 days later. I have seen some solutions using between, but this would also retrieve Max if checking everything in 7 days.

Also, the dates do not have time, only year, month and the day. The reason for this is I want to notify the person only once when the date is 7 days before.

I am new to pandas, so any kind of help is welcome.

CodePudding user response:

This is probably a little verbose but I think it does what you want.

from datetime import datetime, timedelta
import pandas as pd

df = pd.DataFrame({'Id':['Max','Joe','Moe'],
'Source':['2022-03-24','2022-03-30','2022-04-06']
              })

df.Source = pd.to_datetime(df.Source)
df = df.set_index('Source')

def in7days(df):
    now = datetime.now()
    dt = now   timedelta(7)
    idx = df.index.get_loc(dt, method='nearest')
    td = (dt - df.index[idx]).days
    if td != 0:
        return("No entries found.")
    else:
        return(df.iloc[idx])

Then if you call in7days(df) you get the following output:

Id    Moe
Name: 2022-04-06 00:00:00, dtype: object

P.S. I changed the date of Moe so that it was 7 days from today to get a workable example.

  • Related