Last day of month in Python
This small blog post explains how to get the last day of a given month in Python. As example I print a list of months in a given year range. Each line will contain the start- and enddate of that month.
Iterate months in a range of years
The following piece of Python code prints every month in given range of years.
Code
import calendar
for y in range(2014, 2021):
for m in range(1, 13):
w, d = calendar.monthrange(y, m)
print(f'{y}-{m:02d}-01 {y}-{m:02d}-{d}')
Result
2014-01-01 2014-01-31
2014-02-01 2014-02-28
...
2020-11-01 2020-11-30
2020-12-01 2020-12-31
Explained
range(n)
Is of exclusive nature, apply +1 to get inclusive number range.
calendar.monthrange(y, m)
Returns weekday of first day of the month and number of days in month.
{m:02d}
Appends a leading zero to the month number.