Skip to content

Instantly share code, notes, and snippets.

@pebbie
Created December 15, 2012 14:24
Show Gist options
  • Save pebbie/4295544 to your computer and use it in GitHub Desktop.
Save pebbie/4295544 to your computer and use it in GitHub Desktop.
test weekday consistency
import datetime
WEEK = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat']
def dow(dd,mm,yyyy):
return (datetime.date(yyyy, mm, dd).weekday()+1) % 7
#from python datetimemodule.c
def dow_c(dd, mm, yyyy):
y = yyyy - 1
dby = y*365 + y/4 - y/100 + y/400;
_dbm = [0, 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334]
dbm = _dbm[mm]
if is_leap(yyyy) and mm>2: dbm+=1
return (dd + dbm + dby) % 7
def dow_gauss(dd,mm,yyyy):
cc = yyyy / 100
yy = yyyy % 100
return (dd + 26 * (1 + mm) / 10 + 5 * yy / 4 + cc / 4 - 2 * cc - 1) % 7
def is_leap(yyyy):
return yyyy % 4 == 0 and (yyyy % 100 != 0 or yyyy % 400 == 0)
#from http://en.wikipedia.org/wiki/Determination_of_the_day_of_the_week
def dow_tab(dd,mm,yyyy):
def cent(t, c): return t[2][(c-t[0]) % t[1]]
greg_cent = (15, 4, [0,6,4,2])
years = {
1: [1, 7, 12, 18, 29, 35, 40, 46, 57, 63, 68, 74, 85, 91, 96],
2: [2, 13, 19, 24, 30, 41, 47, 52, 58, 69, 75, 80, 86, 97],
3: [3, 8, 14, 25, 31, 36, 42, 53, 59, 64, 70, 81, 87, 92, 98],
4: [9, 15, 20, 26, 37, 43, 48, 54, 65, 71, 76, 82, 93, 99],
5: [4, 10, 21, 27, 32, 38, 49, 55, 60, 66, 77, 83, 88, 94],
6: [5, 11, 16, 22, 33, 39, 44, 50, 61, 67, 72, 78, 89, 95],
0: [6, 17, 23, 28, 34, 45, 51, 56, 62, 73, 79, 84, 90, 0]
}
leap_years = {4:4, 8:2, 12:1, 16:5, 20:3, 24:1, 28:6, 32:4, 36:2, 40:0, 44:5, 48:3, 52:1, 56:6, 60:4, 64:2, 68:0, 72:5, 76:3, 80:1, 84:6, 88:4, 92:2, 96:0, 0:6}
months = [0, 3, 3, 6, 1, 4, 6, 2, 5, 0, 3, 5]
cc = yyyy / 100
yy = yyyy % 100
clut = cent(greg_cent, cc)
for k, v in years.items():
if yy in v:
ylut = k
break
if is_leap(yyyy) and mm < 3:
ylut -= 1
mlut = months[mm-1]
return (dd + mlut + ylut + clut) % 7
def dow_sakamoto(d,m,y):
t = [0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4]
y -= m < 3
return (y + y / 4 - y / 100 + y / 400 + t[m-1] + d) % 7
def test_date(fn,y1,y2):
mm = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 31]
for y in xrange(y1, y2):
if (fn(1,1, y+1) - fn(31,12,y)) % 7 != 1: print "wrong", (fn(31,12,y), (31, 12, y), fn(1,1,y+1), (1, 1, y+1))
for m in xrange(1, 11):
dd = mm[m-1]
if is_leap(y) and m == 2: dd += 1
d1 = fn(dd,m,y)
d2 = fn(1,m+1, y)
if (d2 - d1) % 7 != 1:
print "wrong", (d1, (dd, m, y), d2, (1, m+1, y))
if __name__ == "__main__":
test_date(dow,1600,2500)
test_date(dow_tab,1600,2500)
test_date(dow_sakamoto,1600,2500)
test_date(dow_c,1600,2500)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment