Search code examples
pythonpandas

Calculate 6 months forward date from a dataframe of dates


I have below code

import pandas as pd
from dateutil.relativedelta import relativedelta
date = pd.to_datetime(['2001-01-01', '2003-01-01'])
date + relativedelta(months = +6)

Basically I am trying to calculate 6 months ahead date from a dataframe of dates.

Above code is failing.

TypeError: unsupported operand type(s) for +: 'DatetimeArray' and 'relativedelta'

Could you please help to correct this code?


Solution

  • You can't use Python's datetime utils with Pandas.

    You should use Pandas' DateOffset:

    date = pd.to_datetime(['2001-01-01', '2003-01-01'])
    date + pd.DateOffset(months = +6)
    

    Output:

    DatetimeIndex(['2001-07-01', '2003-07-01'], dtype='datetime64[ns]', freq=None)