How to add a month to a datetime object?

Viewed 78

I am trying to use quarterly variables that are aligned to first quarter, fourth quarter, seventh quarter and so forth. Using business quarters and trying to add one working month to them

start = datetime.date.today()
start=start+pd.tseries.offsets.DateOffset(months=1)
end = datetime.date(start.year+2, 12, 31)
business_days_rng =pd.date_range(start, end, freq='BQ')

but I get a message saying:

Addition/subtraction of integers and integer-arrays with Timestamp is no longer supported. Instead of adding/subtracting n, use n * obj.freq

1 Answers

You can use time delta

datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)

but for longer periods relative delta will be convenient

This uses the python-dateutil extension

from datetime import date
from dateutil.relativedelta import relativedelta

six_months = date.today() + relativedelta(months=+6)

The advantage of this approach is that it takes care of issues with 28, 30, 31 days etc. This becomes very useful in handling business rules and scenarios (say invoice generation etc.)

$ date(2010,12,31)+relativedelta(months=+1)
  datetime.date(2011, 1, 31)

$ date(2010,12,31)+relativedelta(months=+2)
  datetime.date(2011, 2, 28)
Related