How to determine the number of days for a given month in python

I need to calculate the number of days for a given month in python. If the user enters February 2011, the program should be able to tell me that in February 2011 there were 28 days. Can someone tell me which library should I use to determine the length of a given month.

+75
python
Feb 08 2018-11-21T00:
source share
3 answers

Use calendar.monthrange :

 >>> from calendar import monthrange >>> monthrange(2011, 2) (1, 28) 

To be clear, monthrange also supports leap years:

 >>> from calendar import monthrange >>> monthrange(2012, 2) (2, 29) 
+169
Feb 08 2018-11-11T00:
source share

Alternative solution:

 >>> from datetime import date >>> (date(2012, 3, 1) - date(2012, 2, 1)).days 29 
+24
Feb 09 '11 at 13:16
source share

Just for the sake of academic interest, I did it this way ...

 (dt.replace(month = dt.month % 12 +1, day = 1)-timedelta(days=1)).day 
+3
May 30 '13 at 17:13
source share



All Articles