40

Possible Duplicate:
Get Last Day of the Month in Python

How can I get the number of days in the current month? I.e.,if the current month is "Jan 2012" I should get 31. If it is "Feb 2012" I should get 29.

Community
  • 1
  • 1
Alchemist777
  • 1,621
  • 5
  • 21
  • 31

1 Answers1

85

As Peter mentioned, calendar.monthrange(year, month) returns weekday (0-6 ~ Mon-Sun) and number of days (28-31) for year, month.

>>> import calendar
>>> print calendar.monthrange(2012,1)[1]
31
>>> calendar.monthrange(2012,2)[1]
29

Edit: updated answer to return the number of days of the current month

>>> import calendar
>>> import datetime
>>> now = datetime.datetime.now()
>>> print calendar.monthrange(now.year, now.month)[1]
29
BioGeek
  • 21,897
  • 23
  • 83
  • 145
  • Thanks!!!!but i dont want to hardcode the dates like (2012,1)..I want it to be the system date – Alchemist777 Feb 28 '12 at 11:51
  • Thank you so much.This works for windows..i am using ubuntu 11.10..and import calender produces the error "No module named calender"..any ideas??? or is there an alternate method of getting this done without using 'calender'??? – Alchemist777 Feb 28 '12 at 12:04
  • 5
    Note, it is `calendAr` instead of `calendEr`! – BioGeek Feb 28 '12 at 12:07