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

ぃ、小莉子 提交于 2021-01-07 02:32:59

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/65446876/check-if-date-column-is-in-the-range-of-last-3-months-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!