Modules -> OOP -> Case study: Time -> Comparing times

Comparing times


Related code
class Time:
    """Represents the time of day.
    attributes: hour, minute, second
    """

    def set(self, hour, minute, second):
        self.hour = hour
        self.minute = minute
        self.second = second

    def print(self):
        print(f"{self.hour:02}:{self.minute:02}:{self.second:02}")

    def to_seconds(self):
        minutes = self.hour * 60 + self.minute
        seconds = minutes * 60 + self.second
        return seconds

    def add(self, other):
        seconds = self.to_seconds() + other.to_seconds()
        return seconds_to_time(seconds)

    def increment(self, seconds):
        seconds += self.to_seconds()
        return seconds_to_time(seconds)

def seconds_to_time(seconds):
    time = Time()
    minutes, time.second = divmod(seconds, 60)
    time.hour, time.minute = divmod(minutes, 60)
    return time

start = Time()
start.set(9, 45, 0)

end = Time()
end.set(12, 30, 0)

We're going to write a method which compares two times, is_after. One time is after the other if it is later. To know if a time is later than the other we have to first compare hour, then minute, then second. Or, we can take advantage of to_seconds method to convert time to seconds and compare them.

class Time:
    ...
    def is_after(self, other):
        return self.to_seconds() > other.to_seconds()

To use this method, you have to invoke it on one object and pass the other as an argument:

>>> end.is_after(start)
True

Exercises


Add a Time method, add_times, which takes two Time objects as arguments, self and other, and returns a new Time objects which is sum of self and other