Python: Test whether a time falls within an interval

Words
27
Reading
1 min
3h
Listen to this post
~1 min

This small Python script can be used to test whether a given time falls within a specific time interval. It does not rely on the 'datetime' library.

class Time:
    hour: int
    minute: int

    def __init__(self, h: int, m: int):
        self.hour = h
        self.minute = m

    def __str__(self) -> str:
            return f"{self.hour}:{self.minute}"

    def __repr__(self) -> str:
            return f"(hour={self.hour} minute={self.minute})"

    def __eq__(self, other) -> bool:
        if isinstance(other, Time):
            if self.hour == other.hour and self.minute == other.minute:
                return True
            return False
        return False

    def __lt__(self, other) -> bool:
        if isinstance(other, Time):
            if self.hour < other.hour:
                return True
            elif self.hour == other.hour:
                if self.minute < other.minute:
                    return True
                return False
            return False
        return False

    def __gt__(self, other) -> bool:
        if isinstance(other, Time):
            if self.hour > other.hour:
                return True
            elif self.hour == other.hour:
                if self.minute > other.minute:
                    return True
                return False
            return False
        return False

def testTimeInterval(start: Time, end: Time, x: Time) -> str:
    if start < end:
        if x < start:
            return f'{x} is before {start}'
        elif x == start:
            return f'{x} is the same time as {start}'
        elif start < x < end:
            return f'{x} is between {start} and {end}'
        elif x == end:
            return f'{x} is the same time as {end}'
        elif x > end:
            return f'{x} is after {end}'
    elif start > end:
        return "starttime can't be greater then endtime"
    elif start == x == end:
        return "All times are the same"
    return "unknown case"

if __name__ == '__main__':
    start = Time(8,40)
    end = Time(9,20)
    toTest = Time(9,0)
    print(testTimeInterval(start,end,toTest))
Python: Test whether a time falls within an interval | Ecency