To get the days in the month using Python, the easiest way is with the timerange() function from the calendar module to get the number of days in the month.
import calendar
import datetime
currentDate = datetime.date.today()
daysInMonth= calendar.monthrange(currentDate.year, currentDate.month)[1]
print(currentDate)
print(daysInMonth)
#Output:
2022-03-06
31
When working in Python, many times we need to create variables which represent dates and times. When creating and displaying values related to dates, sometimes we want to get the number of days in a month.
To get the number of days in a month, we can use the monthrange function from the calendar module.
The monthrange() function takes in a year and month, and returns the weekday of first day of the month and number of days in month.
We can pass a year and month to monthrange() and then get the number of days of the month accessing the second element of the returned tuple.
Below is a simple example in Python of how to get the number of days in a month of the current date using Python.
import calendar
import datetime
currentDate = datetime.date.today()
daysInMonth= calendar.monthrange(currentDate.year, currentDate.month)[1]
print(currentDate)
print(daysInMonth)
#Output:
2022-03-06
31
How to Get the Last Day of a Month Using Python
With the monthrange() function, we can get the last day of a month in Python easily by adjusting the code from above.
To get the last day of a given month with Python, we can get the number of days in a month using monthrange(), and then create a new date.
Below is how to use Python to create a new date that has the last day of a given month.
import calendar
import datetime
currentDate = datetime.date.today()
lastDayOfMonth = datetime.date(currentDate.year, currentDate.month, calendar.monthrange(currentDate.year, currentDate.month)[1])
print(currentDate)
print(lastDayOfMonth)
#Output:
2022-03-06
2022-03-31
Hopefully this article has been useful for you to learn how to get the number of days in a month using Python.