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.
To get the number of days in the current month:function getDaysInCurrentMonth() { const date = new Date(); return new Date( date. getFullYear(), date. getMonth() + 1, 0 ). getDate(); } const result = getDaysInCurrentMonth(); console.
Each month has 28, 30, or 31 days during a normal year, which has 365 days. A leap year occurs nearly every 4 years which adds an extra day to February. February is the only month with 28 days. There are 30 days in April, June, September and November.
You can use simple date arithmetic to find the number of days between two dates in Python. Define the 2 dates between which you want to find the difference in days. Then subtract these dates to get a timedelta object and examine the day's property of this object to get the required result.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With