跳至内容
liuzhen932 的小窝
返回

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

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

人机验证:请刷新页面以加载评论区