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
122018-01-01      5132018-01-02      6142018-01-03      8152018-01-04      2162018-01-05      5172018-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)]

DateValue122018-01-01      5132018-01-02      6142018-01-03      8152018-01-04      2162018-01-05      5172018-01-06      6

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