W3docs

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.

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:

an example code snippet that gets the last day of the month for the current date in Python

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)

<div class="alert alert-info flex not-prose"> Watch a course <span class="hidden md:block">Watch a video course </span> Python - The Practical Guide</div>

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

an example code snippet that gets the last day of the month for a specific date in Python

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.