如何仅检索列字段值正好比当前时间多 7 天的数据框行?

How to retrieve only dataframe rows where column field values are exactly 7 days more than current time?

我正在尝试从 pandas 数据框中检索特定行,其中列的日期正好比当前时间多 7 天。 例如,当前日期是 2022-03-22。 这是我的数据框:

        name      date              

0       Max     2022-03-24

1       Joe     2022-03-29

2       Moe     2022-04-03

现在我只想检索 Joe,因为他的日期恰好在 7 天后。 我已经看到一些使用 between 的解决方案,但如果在 7 天内检查所有内容,这也会检索 Max。

另外,日期没有时间,只有年月日。 这样做的原因是我只想在日期为 7 天前通知此人一次。

我是 pandas 的新手,欢迎任何帮助。

这可能有点冗长,但我认为它可以满足您的需求。

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])

然后如果你调用 in7days(df) 你会得到以下输出:

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

P.S。我更改了 Moe 的日期,以便从今天开始算起 7 天,以获得一个可行的示例。