[Tutor] Re: Is it a weekend

Magnus Lycka magnus@thinkware.se
Wed, 18 Sep 2002 03:24:47 +0200


At 15:44 2002-09-17 -0700, Emile van Sebille wrote:
>"Michael Montagne" <montagne@boora.com> wrote in message
>news:20020917221312.GB30884@boora.com...
> > Can python tell me if it is a weekend or not?  Holiday?
>
> >>> import time
> >>> time.localtime(time.time())
>(2002, 9, 17, 15, 33, 11, 1, 260, 1)
> >>> print time.localtime.__doc__
>localtime([seconds]) ->
>(tm_year,tm_mon,tm_day,tm_hour,tm_min,tm_sec,tm_wday,tm_
>yday,tm_isdst)

To make it a bit more specific:

import time, types

def weekend(when=None):
     if when == None: # Use present
         when = time.localtime()
     elif type(when) == types.FloatType: # Seconds since epoch
         when = time.localtime(when)
     elif type(when) != type(time.localtime()):
         print type(when)
         raise TypeError, "Bad input, expected float or time-struct"
     iDayOfWeek = 6
     friday = 4 # monday = 0, sunday = 6
     return when[iDayOfWeek] > friday

#test
print weekend()
daylength = 24 * 60 * 60 # seconds
ourTime = time.time()
for d in range(7):
     print weekend(ourTime)
     print weekend(time.localtime(ourTime))
     ourTime += daylength

I'd recommend keeping a dictionary with year and a tuple of
julian day numbers for holidays for each year. Then you just
need something like...

def holiday(when):
     # Assuming time-struct.
     iYear, iJulianDay = 0, 7
     return when[iJulianDay] in holidays[when[iYear]]

...to catch the remaining red days. Of course things like
easter can be calculated, but I wouldn't bother to do that
in run-time.

>Convert seconds since the Epoch to a time tuple expressing local time.
>When 'seconds' is not passed in, convert the current time instead.
> >>>
>
>mxDateTime has Feasts, which covers some of the additional holidays, but
>as there are different observances everywhere, you're not likely to find
>any one module that covers them all the right way.



-- 
Magnus Lycka, Thinkware AB
Alvans vag 99, SE-907 50 UMEA, SWEDEN
phone: int+46 70 582 80 65, fax: int+46 70 612 80 65
http://www.thinkware.se/  mailto:magnus@thinkware.se