How to find number of days in the current month

Question:

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.

Asked By: Alchemist777

||

Answers:

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
Answered By: BioGeek
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.