203

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 anyone tell me which library I should use to determine the length of a given month?

Gavriel Cohen
  • 4,355
  • 34
  • 39
Joel James
  • 2,073
  • 2
  • 13
  • 5

3 Answers3

419

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.

Community
  • 1
  • 1
Andrew Hare
  • 344,730
  • 71
  • 640
  • 635
  • 8
    What (2,29) means? I think it should be (1,28)... – Nam G VU Jan 22 '18 at 19:08
  • 46
    @NamGVU First number is weekday of first day of the month, second number is number of days in said month. – Mikhail Pyrev Feb 08 '18 at 12:38
  • 1
    @NamGVU In 2011, the month of February started on a weekday and had 28 days. In 2012, the first weekday was on the 2nd, and the month had 29 days that year. – Maddie Mar 25 '19 at 14:21
  • 3
    @Maddie Nope, both started on a weekday: Thuesday (`1`) on February 2011 and Wednesday (`2`) on February 2012. The first integer doesn't return weekday, but day of the week. From `0` (Monday) to `6` (Sunday) by default. – Nuno André Apr 02 '19 at 21:54
  • @NunoAndré I know. I was explaining that in the year 2011, the month of February (that's what the 2 is), the first (1) was a weekday. And February had 28 days that year. In 2012, in February (2), the first weekday was on the second (2), and February had 29 days in the year 2012. – Maddie Apr 03 '19 at 22:06
61

Alternative solution:

>>> from datetime import date
>>> (date(2012, 3, 1) - date(2012, 2, 1)).days
29
Björn Lindqvist
  • 19,221
  • 20
  • 87
  • 122
  • 9
    The difficulty with this solution is that if you want to use it for every months for multiple years, you need to take into account the year increment and month cycle. – Yohan Obadia Dec 04 '18 at 10:26
  • that's a simple modulo (because first and last months of the year are always the same) – Guy Feb 08 '21 at 00:08
  • OP states that he wants it for a given month (and year), thus this solution is fine. He needs to check 1 date at a time. You can replace it with vars for the year, month and day to make it more flexible, but this solution works great! – MA53QXR Sep 07 '21 at 09:53
16

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
Mike G
  • 4,232
  • 9
  • 40
  • 66
Frosty Snowman
  • 435
  • 5
  • 5