Link to home
Start Free TrialLog in
Avatar of newparadigmz
newparadigmzFlag for United States of America

asked on

In python, looking for a range of "quarters" from a date range

So with the inputs being from_date=2019-01-01 and to_date=today

I need

2019-01-01 - 2019-03-31
2019-04-01 - 2019-06-30
2019-07-01 - 2019-09-30
2019-10-01 - 2019-12-31
2020-01-01 - 2020-02-04

I don't really know any python, but this is the closest I can come up with so far.
The dates are there, I just don't know how to access them or fill in today's date on the last item....

    def get_date_ranges(self, fr_date, to_date):
        qtr_beg = pd.date_range(start=fr_date, end=datetime.date.today(), freq='QS')
        qtr_end = pd.date_range(start=fr_date, end=datetime.date.today(), freq='Q')
        date_range = zip(qtr_beg, qtr_end)
        return date_range

Open in new window

Avatar of noci
noci

Try this:


def get_date_ranges(fr_date, to_date):
        qrange=pd.period_range(start=fr_date,end=to_date,freq='Q')
        qtr_beg = qrange.asfreq('D','s')
        qtr_end = qrange.asfreq('D','e')
        date_range = zip(qtr_beg, qtr_end)
        return date_range

Open in new window

Avatar of newparadigmz

ASKER

How do I use it, to access the dates inside?
Do you mean you want to list all the dates for each quarter?
import pandas as pd

def get_date_ranges(fr_date, to_date):
         qrange=pd.period_range(start=fr_date,end=to_date,freq='Q')
         qtr_beg = qrange.asfreq('D','s')
         qtr_end = qrange.asfreq('D','e')
         date_range = zip(qtr_beg, qtr_end)
         return date_range

for x in get_date_ranges('2018-02-01','2020-06-30'):
  print(x)

Open in new window

which delivers:

(Period('2018-01-01', 'D'), Period('2018-03-31', 'D'))
(Period('2018-04-01', 'D'), Period('2018-06-30', 'D'))
(Period('2018-07-01', 'D'), Period('2018-09-30', 'D'))
(Period('2018-10-01', 'D'), Period('2018-12-31', 'D'))
(Period('2019-01-01', 'D'), Period('2019-03-31', 'D'))
(Period('2019-04-01', 'D'), Period('2019-06-30', 'D'))
(Period('2019-07-01', 'D'), Period('2019-09-30', 'D'))
(Period('2019-10-01', 'D'), Period('2019-12-31', 'D'))
(Period('2020-01-01', 'D'), Period('2020-03-31', 'D'))
(Period('2020-04-01', 'D'), Period('2020-06-30', 'D'))

Open in new window

The input arrays are the dates generated from period_range and from there the first (qtr_beg) & last (qtr_end) are derived.

The zip function (python built-in) creates pair of numbers from two input arrays (qtr_beg, qtr_end)


ASKER CERTIFIED SOLUTION
Avatar of newparadigmz
newparadigmz
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial