Given a year and a month, I want to determine the last day of that month. For example, if the year is 2004 and the month is 2, then the last day is 29th because of leap year.
Calculating the last day of a month is not hard, but complicated by the leap year. If the year is a leap year, then February’s last day will be 29th instead of the usual 28th. My algorithm to find the last day of the month is simpler than that: take the first day of the next month and count backward by one day. Here is the code.
#!/usr/bin/env python import datetime def get_last_day_of_the_month(y, m): ''' Returns an integer representing the last day of the month, given a year and a month. ''' # Algorithm: Take the first day of the next month, then count back # ward one day, that will be the last day of a given month. The # advantage of this algorithm is we don't have to determine the # leap year. m += 1 if m == 13: m = 1 y += 1 first_of_next_month = datetime.date(y, m, 1) last_of_this_month = first_of_next_month + datetime.timedelta(-1) return last_of_this_month.day
The code above is easy enough to understand. The datetime.timedelta(-1) on line 22 basically says, “subtract one day.”