[Tutor] Comparing Time.

Jeff Shannon jeff@ccvcorp.com
Tue, 30 Jul 2002 10:29:33 -0700


Colin Campbell wrote:

> At 07:02 PM 7/29/02, you wrote:
>
>> "As a second exercise, write a boolean function after that takes
>> two
>> Time objects, t1 and t2, as arguments, and returns true (1) if t1
>> follows t2 chronologically and false (0) otherwise. "
>>
>> And the Time object is a very simple object with 3 attributes:
>> hours,
>> minutes, seconds.  [....]
>
> import time
> def bigtime(t1, t2)
> return t1 > t2
>
> ### sample values
> t1 = time.gmtime
> t2 = time.localtime

Well, the problem stated above indicates that the time values in use
are special class-objects with three attributes, *not*
seconds-since-epoch time values.  Besides which... you're not really
getting time values there.  You didn't add parentheses at the end of
your functions, there, so you never called them -- you just assigned
references.  Thus, t1() is now effectively an alias for time.gmtime().

Looking at the original problem, we have a class that looks like this:

class TimeObj:
    def __init__(self, hour, min, sec):
        self.hour = hour
        self.min = min
        self.sec = sec

Now, I will make one assumption about our time values, that they are
all normalized -- that is, that we will never have more than 60
minutes or more than 60 seconds.  With that presumption, we can then
take advantage of Python's rules for comparing sequences -- the first
element is compared first, and if that matches the second element is
compared, and if that matches the third is compared, etc...

def CompareTime(t1, t2):
    left = (t1.hour, t1.min, t1.sec)
    right = (t2.hour, t2.min, t1.sec)
    return left > right

Actually, as an interesting aside, when I tested this out in the
interpreter, I found that the TimeObj class I had above compared
correctly even *without* the CompareTime() function --

>>> t1 = TimeObj(5, 35, 15)
>>> t2 = TimeObj(12, 45, 5)
>>> t3 = TimeObj(17, 10, 45)
>>> t1 > t2
0
>>> t2 > t3
0
>>> t3 > t1
1

However, it is only happy coincidence that the default compare seems
to be comparing attributes in the correct order.  (I presume that it's
comparing each instance's __dict__, and that 'hours' just happens to
hash first...)  This is not something to rely on, thus the
CompareTime() function explicitly specifies which attributes are most
significant.

Jeff Shannon
Technician/Programmer
Credit International