Find years with same calendar

From CodeCodex

Given a particular year, this script will find prior years, back to some arbitrary limit (currently set to 1970), that share the same calendar. This can be useful, e.g. for working with ancient electronic devices or operating systems, whose valid ranges of dates don't extend up to the present, so you can set them to the same date as the present in a year that they will accept, and have it show the same day of the week.

This script also does partial matches, which is useful for leap years, in case no actual leap-year match can be found in the right range. A partial match will share the same calendar either from 1st January to 28th February, or from 1st March to 31st December. 29th February will have no match because one year is leap and the other isn't.

For instance, running the command

samecal 2009

produces the output

 2004 <= 28 Feb
 1992 >= 1 Mar
 1976 <= 28 Feb

which means that 1998, 1987, 1981 and 1970 all share the exact same calendar as 2009, while 2004 and 1976 only match in the part up to 28th February, and 1992 only matches from 1st March onwards.


import sys
import calendar

def dayofweek(year, month, day) :
    """returns the day of week for the specified date [0 .. 6] => [Sun .. Sat]."""
    return (calendar.weekday(year, month, day) +1) % 7
#end dayofweek

def yearsig(year) :
    """returns a tuple of 2 integers, being the day of week for 1st January and 1st March
    for the specified year."""
    return dayofweek(year, 1, 1), dayofweek(year, 3, 1)
#end yearsig

# Mainline

if len(sys.argv) != 2 :
    raise RuntimeError("need exactly one arg, the year number")
#end if
year = int(sys.argv[1])
match_sigA, match_sigB = yearsig(year)
min_year = 1970
for year in xrange(year-1, min_year-1, -1) :
    sigA, sigB = yearsig(year)
    if sigA == match_sigA :
        if sigB == match_sigB :
            print year
        else :
            print year, "<= 28 Feb"
        #end if
    elif sigB == match_sigB :
        print year, ">= 1 Mar"
    #end if
#end while