[Tutor] help with dates

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Tue Jul 29 16:38:01 2003


On Tue, 29 Jul 2003, james middendorff wrote:

> I am attempting to write a little program that will tell you on which
> day a certain holiday will fall. In whatever year you want. I am a
> beginner and was wondering how I should tackle this project, or is
> someone could point my in the right direction? Thanks for any help


Hey James, long time no chat.  *grin*


For holidays that are consistently held on a certain day, you may be able
to use the 'calendar' module (or maybe not!  Read below.):

    http://www.python.org/doc/lib/module-calendar.html


It has a function called 'weekday()' that sounds almost right:

###
>>> calendar.weekday(2003, 7, 29)
1
###


weekday() returns the day number (0 is monday, 1 is tuesday, etc...).



The only problem with it is that it depends on a certain function that's
limited to dates after 1970!  The reason for it is this: calendar uses the
time module, which itself depends on the computer system clock.  And all
computer clocks start, not at Year 0, but at the "Epoch" (January 1970).
If we try going below that range, we'll hit an error:


###
>>> calendar.weekday(1009,7,29)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "/home/dyoo/local/Python-2.2.1/lib/python2.2/calendar.py", line
106, in weekday
    secs = mktime((year, month, day, 0, 0, 0, 0, 0, 0))
ValueError: year out of range
###


So the straightforward approach, using the 'calendar' module, probably
isn't robust enough for your problem.




For more serious date-time stuff, you may want to look at the mx.DateTime
module instead:

    http://www.lemburg.com/files/python/mxDateTime.html

And here, it works:

###
>>> import mx.DateTime
>>> date = mx.DateTime.DateTime(1009, 7, 29)
>>> date.day_of_week
5
###



Hope this helps!