Creating a data range with Python

In [1]:
import datetime
In [2]:
def get_daterange_in_days(start_date, end_date):
    """ Return days between start and end date """
    start_date = datetime.datetime.strptime(start_date, "%Y-%m-%d").date()
    end_date = datetime.datetime.strptime(end_date, "%Y-%m-%d").date()
    for n in range(int((end_date - start_date).days)):
        yield start_date + datetime.timedelta(n)
In [3]:
for day in get_daterange_in_days('2019-03-01', '2019-03-07'):
    print(f"Current day: {day}")
Current day: 2019-03-01
Current day: 2019-03-02
Current day: 2019-03-03
Current day: 2019-03-04
Current day: 2019-03-05
Current day: 2019-03-06
In [4]:
def get_daterange_in_months(start_month, end_month):
    """ Returns the months between start and end month """
    start_month = datetime.datetime.strptime(start_month, "%Y-%m").date()
    end_month = datetime.datetime.strptime(end_month, "%Y-%m").date()
    while start_month <= end_month:
        if start_month.month >= 12:
            next = datetime.date(start_month.year + 1, 1, 1)
        else:
            next = datetime.date(start_month.year, start_month.month + 1, 1)
        last = min(next - datetime.timedelta(1), end_month)
        yield (start_month.strftime('%Y-%m'), start_month, last)
        start_month = next
In [5]:
for month in get_daterange_in_months('2019-01', '2019-03'):
    current_month, startdate, enddate = month
    print(f'Current month: {current_month}')
Current month: 2019-01
Current month: 2019-02
Current month: 2019-03