[Solved] date_range generator last 30 days Python [closed]


You should create an empty list and keep appending the dates:

import datetime


def date_range():
    result = []

    current = datetime.date(2021, 3, 1)
    end = datetime.date(2021, 3, 31)
    delta = datetime.timedelta(days=1)

    while current <= end:
        result.append(current)
        current += delta

    return result

print(date_range())

Of course, you can pass start and end as parameters, which makes much more sense:

import datetime


def date_range(start, end):
    result = []

    current = start
    delta = datetime.timedelta(days=1)
    while current <= end:
        result.append(current)
        current += delta

    return result


print(date_range(datetime.date(2021, 3, 1), datetime.date(2021, 3, 31)))

If you want them as strings:

import datetime


def date_range(start, end):
    result = []

    current = start
    delta = datetime.timedelta(days=1)
    while current <= end:
        result.append(current.strftime("%Y-%m-%d"))
        current += delta

    return result


print(date_range(datetime.date(2021, 3, 1), datetime.date(2021, 3, 31)))

If you only need to iterate over them, you can yield them all and there is no need to create a list:

def date_range(start, end):
    current = start
    delta = datetime.timedelta(days=1)
    while current <= end:
        yield current
        current += delta


for date in date_range(datetime.date(2021, 3, 1), datetime.date(2021, 3, 31)):
    print(date)

2

solved date_range generator last 30 days Python [closed]