from datetime import date, datetime, timedelta
#Generator function that returns an iterator for a date object
#start date: begin
#End date: end
def date_iterator_generator(begin, end):
#Find the number of days from the timedelta of the end date and start date
#To include the end date+1
length = (end - begin).days + 1
#Numerical sequence from 0 to days
for n in range(length):
yield begin + timedelta(n)
#Start date / end date
begin = datetime.strptime('20200331', '%Y%m%d').date()
end = date.today() #Today's date
#Generate generator
gen = date_iterator_generator(begin, end)
print('gen: ' + str(gen))
#Output date
for target in gen:
print(target.strftime('%Y%m%d'))
The result of running with Python 3.8.2.
gen: <generator object date_iterator_generator at 0x104e0f900>
20200331
20200401
20200402
20200403
20200404
20200405
Functional Programming HOWTO — Python 3 \ .8 \ .2 Documentation
Generators are special functions that make it easier to write iterators. A standard function calculates and returns a value, but the generator returns an iterator that returns a set of values.
Built-in — Python 3 \ .8 \ .2 documentation
The range type represents an immutable sequence of numbers and is commonly used in for loops for a certain number of loops.
datetime ---Basic date and time types — Python 3 \ .8 \ .2 documentation
The timedelta object represents the elapsed time, that is, the difference between two dates or times.