paddu
paddu

Reputation: 713

Get last day of month in python

Getting error for December month.

ValueError: month must be in 1..12

def last_day_of_month(ds):
    cur_ds = datetime.strptime(ds, '%Y-%m-%d')
    next_month = datetime(year=cur_ds.year, month=cur_ds.month+1, day=1)
    last_day_month = next_month - timedelta(days=1)
    return datetime.strftime(last_day_month, '%Y-%m-%d')

print last_day_of_month('2016-12-01')

Upvotes: 2

Views: 21312

Answers (4)

Saad Mirza
Saad Mirza

Reputation: 1177

this is how I did it.

from django.utils import timezone
from calendar import monthrange
from datetime import datetime


current = timezone.now()
firstdayofmonth = current.replace(day=1)
endmonth = monthrange(current.year, current.month)
lastdayofmonth = datetime(current.year, current.month, endmonth[1])

Upvotes: 0

umutto
umutto

Reputation: 7690

In line 3 month=cur_ds.month+1 you are giving 13th month which is not valid. If you want to calculate last day of a given month you could also use month range from calendar library.

>>import calendar
>>year, month = 2016, 12
>>calendar.monthrange(year, month)[1]
31

Upvotes: 10

Matt L
Matt L

Reputation: 1

You're passing in 12 as current month, then adding one to get next_month, making it 13. Check for the 12 case and set month=1 instead.

Upvotes: 0

ShadowRanger
ShadowRanger

Reputation: 155363

You can't make a datetime with a month of 13. So you have to find a way to fix it. A simple solution is to convert the incremented month to an extra year:

# Reduce 12 to 1, 0 and all other #s to 0, #
extrayear, month = divmod(cur_ds.month, 12)
# Add 1 or 0 to existing year, add one to month (which was reduced to 0-11)
next_month = datetime(year=cur_ds.year + extrayear, month=month + 1, day=1)

Upvotes: 2

Related Questions