[Tutor] working with time spans ?

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Fri Jun 4 16:49:37 EDT 2004



On Fri, 4 Jun 2004, Michele Alzetta wrote:

> I've taken a look at modules datetime and calendar, but they don't seem
> to have what I need (or maybe I ca't see it); I would like to be able to
> do something like this:
>
> say this moment is 11 a.m. of 11 september 2002 and the timespan 'a' I'm
> examining is from 1 to 30 september 2002 whereas timespan 'b' is from 12
> to 15 september 2002:


> thismoment in atimespan
> True
>
> thismoment in btimespan
> False


Hi Michele,


I don't see time spans explicitely defined in the datetime module, but we
should be able to do something like this:

###
>>> start, end = (datetime.date(month=9, day=1, year=2002),
...               datetime.date(month=9, day=30, year=2002))
>>>
>>> someOtherDate = datetime.date(month=9, day=11, year=2002)
>>>
>>> start <= someOtherDate <= end
True
>>> start <= end <= someOtherDate
False
###


And if we really wanted to, we can define a Span object that supports the
'in' containment operator, given two endpoints.

###
>>> class Span:
...     def __init__(self, a, b):
...         self.a, self.b = a, b
...     def __contains__(self, x):
...         return self.a <= x <= self.b
...
>>> s = Span(5, 6)
>>> 4 in s
False
>>> 5 in s
True
>>> 5.5 in s
True
>>> 6 in s
True
>>> 7 in s
False
###

This should work on endpoints that are dates, too.



Hope this helps!




More information about the Tutor mailing list