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

Python

Python Problem Overview


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.

Python Solutions


Solution 1 - Python

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.

Solution 2 - Python

Alternative solution:

>>> from datetime import date
>>> (date(2012, 3, 1) - date(2012, 2, 1)).days
29

Solution 3 - Python

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJoel James View Question on Stackoverflow
Solution 1 - PythonAndrew HareView Answer on Stackoverflow
Solution 2 - PythonBjörn LindqvistView Answer on Stackoverflow
Solution 3 - PythonFrosty SnowmanView Answer on Stackoverflow