Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find number of days in the current month [duplicate]

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.

like image 923
Alchemist777 Avatar asked Feb 28 '12 11:02

Alchemist777


People also ask

How do you calculate the number of days in current month?

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.

How many days are there in each month?

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.

How do I calculate the number of days between two dates in Python?

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.


1 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
like image 69
BioGeek Avatar answered Oct 06 '22 04:10

BioGeek