Python – Getting the Number of Days in a Month

The built-in calendar module gives you this useful list:

>>> calendar.mdays
[0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]

As an example of using it, here I get the number of days in the current month:

>>> import calendar
>>> import datetime
>>> calendar.mdays[datetime.date.today().month]
31

BTW this would also tell you the last day of a month.

Fine Print:

I’m not sure how this handles leap years. Perhaps mdays is for the current year? In any case, if you want something more robust you could try this:
[0]+[calendar.monthrange(year,month)[1] for year in [2006] for month in range(1,13)]
in place of calendar.mdays since you provide it with the year to use.

Found that idea in the comments here.

3 Responses to “Python – Getting the Number of Days in a Month”

  1. Brett Hoerner says:

    For the record, the source of calendar.py (hooray open source!) shows:

    # Number of days per month (except for February in leap years)
    mdays = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]

    So it doesn’t currently (as of 2.5) do anything fancy and dynamic.

  2. Thanks Brett. Open source is great. I do my robust method above is leap year sensitive …

  3. do hope that is *