Question
Asked By – Joel James
I need to calculate the number of days for a given month in python. If a user inputs Feb 2011 the program should be able to tell me that Feb 2011 has 28 days. Could any one tell me which library I should use to determine the length of a given month.
Now we will see solution for issue: How do we determine the number of days for a given month in python [duplicate]
Answer
You should use calendar.monthrange
:
>>> from calendar import monthrange
>>> monthrange(2011, 2)
(1, 28)
Just to be clear, monthrange
supports leap years as well:
>>> from calendar import monthrange
>>> monthrange(2012, 2)
(2, 29)
As @mikhail-pyrev mentions in a comment:
First number is the weekday of the first day of the month, the second number is the number of days in said month.
This question is answered By – Andrew Hare
This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0