Search code examples
pythonpandasdateoffset

Find next Quarter/Month/Year/Bi-annual Date from Pandas Timestamp


I want to find a way that could give me next month/quarter/year/bi-annual date given a Pandas timestamp.

If the timestamp is already an end of month/quarter/year/bi-annual date than I can get next quarter date as follows:

pd.Timestamp('1999-12-31') + pd.tseries.offsets.DateOffset(months=3)

What if the time stamp was pd.Timestamp('1999-12-30'), the above won't work.

Expected output

input = pd.Timestamp('1999-12-30')
next_quarter_end = '2000-03-31'
next_month_end = '2000-01-31'
next_year_end = '2000-12-31'
next_biannual_end = '2000-06-30'

Solution

  • This works. I used pandas.tseries.offsets.QuarterEnd, .MonthEnd, and .YearEnd, multiplied by specific factors that change based on the input, to achieve the four values you're looking for.

    date = pd.Timestamp('1999-12-31')
    month_factor = 1 if date.day == date.days_in_month else 2
    year_factor = 1 if date.day == date.days_in_month and date.month == 12 else 2
    next_month_end = date + pd.tseries.offsets.MonthEnd() * month_factor
    next_quarter_end = date + (pd.tseries.offsets.QuarterEnd() * month_factor)
    next_year_end = date + pd.tseries.offsets.YearEnd() * year_factor
    next_biannual_end = date + pd.tseries.offsets.DateOffset(months=6)