[Tutor] working with time spans ?

Michele Alzetta michele.alzetta at aliceposta.it
Sat Jun 5 16:31:07 EDT 2004

[Tim, gives an interesting explanation of *]

Thanks Tim, I must say this escaped me in all my tutorial browsing !

Here is the latest product I came up with:

from datetime import datetime, date, timedelta

class TimeSpan(object):
    ''' I thought it might be useful to check if a timespan 
     is contained in another but also if a single moment
     is contained in another, so I added the isTimeSpan
     attribute and the exception '''
    def __init__(self, startimetuple, endtimetuple):
        self.starttime = datetime(*startimetuple)
        self.endtime = datetime(*endtimetuple)
	self.isTimeSpan = True
    def __contains__(self, timespan):
	    if timespan.isTimeSpan:
                return (self.starttime <= timespan.starttime) and \
                       (self.endtime >= timespan.endtime)
	except AttributeError:
            moment = datetime(*timespan)
	    return (self.starttime <= moment <= self.endtime)
    def length(self):
        return self.endtime - self.starttime

class Shift(TimeSpan):
    '''This derived class knows if the shift is a weekend or night
       shift, and won't accept shifts longer than 12 hours;
       doc, hol and label attributes will come in handy later on
       for the moment they're just here as placeholders'''
    def __init__(self, startimetuple, endtimetuple, doc = None, \
                 night = True, hol = False, weekend = False,   \
                 label = None):
        self.starttime = datetime(*startimetuple)
        self.endtime = datetime(*endtimetuple)
	self.isTimeSpan = True
        self.doc = doc
        self.night = night
        self.weekend = weekend
        self.hol = hol
        self.label = label
        if date.weekday(datetime.date(datetime(*startimetuple))) >= 5:
            self.weekend = True
        self.startday = self.starttime.day
        self.endday = self.endtime.day
        if self.startday == self.endday:
            self.night = False
        max = timedelta(hours = 12)
        assert self.length() <= max

Although not complete by any means, this actually seems to work, so I
was wandering if the end product of my program (not the pretty output, I
mean the 'content' i.e. the program's representation of a monthly shift
schedule) might not be a shelve list (containing an instance of my Shift
class for every single shift as elements) ... or maybe even a shelve

However - wouldn't this be __very__ laborious in terms of memory and cpu
usage ?? Probably using a postgres database would be more efficient, but
I would like to keep things as independent from other programs as
possible (if it ever comes to the point where it passes from an
excercise in python learning to something actually useful, having to
bundle python + postgresql with the program would be a major nuisance).


More information about the Tutor mailing list