How to get the last day of the month?

You can use the calendar.monthrange() function from the calendar module in Python to get the last day of a month. The monthrange() function takes in two arguments: the year and the month, and returns a tuple containing the first day of the week and the last day of the month. Here's an example code snippet that gets the last day of the month for the current date:

import calendar
from datetime import datetime

# Get the current year and month
now = datetime.now()
year = now.year
month = now.month

# Get the last day of the month
_, last_day = calendar.monthrange(year, month)
print(last_day)

Watch a course Python - The Practical Guide

You can also pass in a specific date to get the last day of the month for that date, like this:

import calendar
from datetime import datetime

date = datetime(2022, 12, 10)
year = date.year
month = date.month

_, last_day = calendar.monthrange(year, month)
print(last_day)

This will return 31.