Skip to content

How to Get the Number of Days in a Month in Python

Published: at 00:37编辑

If you need to get the number of days in a month in Python, you can do that quite quickly.

We are going to do that using the calendar module.

First, import the calendar module and then call the method monthrange() which returns the first_day and also the number_of_days in a month.

Let us see this example:

 import calendar

 # Get current month
 _, number_of_days = calendar.monthrange(2022, 12)

 print(number_of_days)  # 31

We can use this method to even check whether a year is a leap year or not:

 import calendar

 # Get current month
 year = 2023

 while True:
     _, number_of_days = calendar.monthrange(year, 2)

     if number_of_days == 29:
         print("February has 29 days in {}".format(year))
         break

     year += 1

I hope you find this useful.


上一篇
How to Make an HTTP Request in JavaScript
下一篇
Top 3 free language learning apps

评论加载中.. 如无法加载请刷新页面