Welcome, guest | Sign In | My Account | Store | Cart

This simple function returns the day of the week (as an integer from 1 to 7) from an input date.....

Python, 35 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# 22-01-04
#
# Date Utils
# By Fuzzyman see www.voidspace.org.uk/atlantibots/pythonutils.html

def datetoday(day, month, year):
    d = day
    m = month
    y = year
    if m < 3:
        z = y-1
    else:
        z = y
    dayofweek = ( 23*m//9 + d + 4 + y + z//4 - z//100 + z//400 )
    if m >= 3:
        dayofweek -= 2
    dayofweek = dayofweek%7
    return dayofweek



months = [ 'january', 'february', 'march', 'april', 'may', 'june', 'july',
          'august', 'september', 'october', 'november', 'december' ]

days =[ 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday',
       'Sunday' ]

d = int(raw_input("Day of the month 1-31 >>"))
m = int(raw_input("Month 1-12 >>"))
y = int(raw_input("Year e.g. 1974 >>"))


dayofweek = days[datetoday(d, m, y)-1]

print dayofweek

This is a python implementation of the formula given at http://users.aol.com/s6sj7gt/mikecal.htm

2 comments

Raymond Hettinger 17 years, 9 months ago  # | flag

Clean. This is a nice example of clean coding in Python.

This particular example is already builtin to the standard library. See calendar.weekday().

Michael Foord (author) 17 years, 7 months ago  # | flag

More Functions and too many batteries. I wrote this function as part of a set of date handling functions, for an administrative tool I was making (which works very nicely thank you !). The rest of the functions can be found at :

http://www.voidspace.org.uk/atlantibots/pythonutils.html

I only recently discovered the calender module in the standard library - which has about a third of my functions already coded !! Python just has too many batteries............

Created by Michael Foord on Thu, 22 Jan 2004 (PSF)
Python recipes (4591)
Michael Foord's recipes (20)

Required Modules

  • (none specified)

Other Information and Tasks