Calculate end of quarter dates

Viewed 112

I am trying to find all the end of quarter dates between two dates. I would also like to use the maximum date for the current / in-progress quarter.

def calculate_quarters(start_yyyy_mm_dd, end_yyyy_mm_dd):
     ...
     ...
     ...

x = calculate_quarters('2020-01-01', '2021-01-07')
print(x)

> ['2020-03-31', '2020-06-30', '2020-09-30', '2020-12-31', '2021-01-07']

I have looked at some previous answers and see we can calculate the end of quarter like this:

>>> d = datetime.date.today()
>>> datetime.date(year=d.year, month=((d.month % 3) + 1) * 3 + 1, day=1) - datetime.timedelta(days=1)
datetime.date(2015, 9, 30)

However I'm unsure how to adapt it to a range and handle incomplete quarters.

1 Answers

If need matching only quarters between both dates use period_range for quartes, convert to timestamps by PeriodIndex.to_timestamp, floor by DatetimeIndex.normalize and last add last incomplete end timestamp if not exist in range by Index.union:

def calculate_quarters(s, e):
    r = pd.period_range(s, e, freq='Q').to_timestamp(how='end').normalize()
    return r[(r > s) & (r < e)].union(pd.to_datetime([e])).strftime('%Y-%m-%d').tolist()


print (calculate_quarters('2020-01-01', '2021-01-07'))
['2020-03-31', '2020-06-30', '2020-09-30', '2020-12-31','2021-01-07']
               

def calculate_quarters(s, e):
    r = pd.period_range(s, e, freq='Q').to_timestamp(how='end').normalize()
    return r[(r > s) & (r < e)].union(pd.to_datetime([e])).strftime('%Y-%m-%d').tolist()


print (calculate_quarters('2020-01-01', '2020-12-31'))
['2020-03-31', '2020-06-30', '2020-09-30', '2020-12-31']
Related