not just random

June 27, 2006

Computing the day of week

Filed under: Algorithms, python — Alex @ 11:50 pm

Here is a nice gem of an algorithm by Kim S. Larsen to compute the day of the week, where m, d and y represent month, day and year, respectively.

def dow(m, d, y):
    if ((m == 1) or (m == 2)):
        m += 12
        y -= 1
    return (d + 2 * m + 3 * (m + 1) / 5 +
    y + y / 4 - y / 100 + y / 400) % 7

The returned integer is a value between 0 (Monday) and 6 (Sunday).

Combine it with a list of day strings:

days = ('Monday', 'Tuesday', 'Wednesday',
'Thursday', 'Friday', 'Saturday', 'Sunday')

Like in the following example to display the name of day, given a date:

days[dow(6, 28, 2006)]

I found the algorithm in Dr. Dobbs Journal issue 229 (April 1995) and the article features a very nice description of how the formula was derived. The original C implementation of the algorithm is about as readable as the above pieces of code.

Leave a Reply