Search code examples
python-3.xdatedatetimepython-dateutil

Check if date column is in the range of last 3 months in Python


Given a small dataset as follow:

   id        date
0   1  2020-01-01
1   2  2020-12-02
2   3  2020-09-26
3   4  2020-05-04
4   5  2020-01-05

I want to check if date is in the range of 3 months from now (since today if 2020-12-25, then the range will be [2020-09-25, 2020-12-25]), if not, then return new columns check with N.

The expected result will like:

   id        date check
0   1  2020-01-01     N
1   2  2020-12-02   NaN
2   3  2020-09-26   NaN
3   4  2020-05-04     N
4   5  2020-01-05     N

How could I do that in Python? Thanks.


Solution

  • The following solution works:

    import datetime 
    import dateutil.relativedelta
    
    start_date = (datetime.datetime.now() + dateutil.relativedelta.relativedelta(months=-3)).strftime('%Y-%m-%d')
    end_date = datetime.datetime.now().strftime('%Y-%m-%d')
    
    mask = df['date'].between(start_date, end_date, inclusive=True)
    df.loc[~mask, 'check'] = 'N'
    

    Out:

       id        date check
    0   1  2020-01-01     N
    1   2  2020-12-02   NaN
    2   3  2020-09-26   NaN
    3   4  2020-05-04     N
    4   5  2020-01-05     N