Determine the Last Day of a Month

The Problem

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.

The Solution

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

Discussion

The code above is easy enough to understand. The datetime.timedelta(-1) on line 22 basically says, “subtract one day.”

6 thoughts on “Determine the Last Day of a Month

  1. Hai Post author

    Donald: Excellent. I am not familiar with Python, thus the run-around algorithm. In fact Python has something similar to that: calendar.monthrange(2004, 2)[1]

  2. David Workman

    Ruby on Rails (so with ActiveSupport’s datetime extensions):

    DateTime.parse(“#{y}/#{m}/1”).end_of_month.day

  3. Rod.ne3

    I do not know if this is relevant. But in bash. Using date (GNU coreutils) 6.10

    date –date=”1 day ago” “+%Y-%m-%d”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s