Skip to content Skip to sidebar Skip to footer

How To Extract Data From Previous 2 Years Based On Particular Date In Python?

I have a csv file consisting of last 3 years of timeseries monthly data. Based on today's date, I would like to read only the previous 2 years of data for forecasting the future. D

Solution 1:

You can try the following

>>> from dateutil.relativedelta import relativedelta
>>> df[df.Date > datetime.now() - relativedelta(years=2)]
         Date  Value
12 2018-01-01      5
13 2018-01-02      6
14 2018-01-03      8
15 2018-01-04      2
16 2018-01-05      5
17 2018-01-06      6

Update

>>> from dateutil.relativedelta import relativedelta
>>> from datetime import date

>>> start_date = pd.Timestamp(datetime.now() - relativedelta(years=2))
>>> end_date = pd.Timestamp(date(date.today().year-1, 12, 31))

>>> df[(df.Date >= start_date) & (df.Date <= end_date)]

         Date  Value
12 2018-01-01      5
13 2018-01-02      6
14 2018-01-03      8
15 2018-01-04      2
16 2018-01-05      5
17 2018-01-06      6

Post a Comment for "How To Extract Data From Previous 2 Years Based On Particular Date In Python?"