tsando
tsando

Reputation: 4717

add x business months to a date in pandas

Does anyone know how to add x business months to a datetime object with pandas? I know you can do this for business days as, e.g.:

datetime.datetime(2017, 11, 23) + pd.tseries.offsets.BDay(20)

Or you can add a month as:

datetime.datetime(2017, 11, 23) + pd.tseries.offsets.DateOffset(months=1)

But this is not giving the correct date for a business month but rather a calendar month. My definition of a business month is to exclude weekends and US Holidays for example.

Any ideas? Thanks!

Upvotes: 1

Views: 1063

Answers (2)

Luigi Sgro
Luigi Sgro

Reputation: 649

When the business day convention is Following:

  1. Add n solar months, as in your example
  2. Add 0 business days. This will adjust the date to match the first following business day, only in case the result of the first calculation doesn't fall on a business day.

The code above modified accordingly:

from datetime import datetime
from pandas.tseries.offsets import DateOffset, BDay

datetime(2017, 11, 23) + DateOffset(months=1) + BDay(0)

This seems to work for me. I am using pandas 0.25.1 on python 3.7.4.

Upvotes: 1

tsando
tsando

Reputation: 4717

Actually I just realised a potential solution for 1 business month (defined as excluding weekends and US holidays) could be:

pd.tseries.offsets.BMonthEnd().rollforward(date) + pd.tseries.offsets.BDay(1)

Upvotes: 1

Related Questions