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

Time:11-07

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'

CodePudding user response:

This works. I used pandas.tseries.offsets.QuarterEnd, .MonthEnd, and .YearEnd, multplied 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)

CodePudding user response:

Technically, the next quarter end after Timestamp('1999-12-30') is Timestamp('1999-12-31 00:00:00')

You can use pandas.tseries.offsets.QuarterEnd

>>> pd.Timestamp('1999-12-30')   pd.tseries.offsets.QuarterEnd()
Timestamp('1999-12-31 00:00:00')

>>> pd.Timestamp('1999-12-30')   pd.tseries.offsets.QuarterEnd()*2
Timestamp('2000-03-31 00:00:00')

Similarly, use pandas.tseries.offsets.MonthEnd() and pandas.tseries.offsets.YearEnd()

For biannual, I guess you can take 2*QuarterEnd().

  • Related