Modules -> OOP -> Case study: Time -> Displaying time

Displaying time


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

t = Time()
t.set(9, 59, 0)

If we want to know the exact time we have to print each of its attributes:

>>> print(t.hour, t.minute, t.second)
9 59 0

Time is usually displayed in the following format:

    hour:minute:second

so, let's update the above statement to print time in the correct format:

>>> print(f"{t.hour}:{t.minute}:{t.second}")
9:59:0

In fact each of the time values should be two digits:

    09:59:00

The format sequence {:02} is used to format an integer in a way that ensures it is printed with at least two digits, including a leading zero if necessary. This is particularly useful for displaying numbers in a consistent and visually appealing manner.

>>> f"{5:02}"
'05'
>>> f"{15:02}"
'15'
>>> f"{154:02}"
'154'

Let's modify the print statement to ensure that each time value has two digits:

>>> print(f"{t.hour:02}:{t.minute:02}:{t.second:02}")
09:59:00

Great. Now we don't want to write this whole statement anytime we want to know the time. So, let's write a Time print method which tells us the time anytime we call it:

class Time:
    ...

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

...
>>> t.print()
09:59:00

Exercises


Write a function named print_time that takes a Time object and prints it in the form hour:minute:second. Examples:

	10:02:11
	01:22:09
	12:09:00



Write a boolean function named is_after that takes two Time objects, t1 and t2, and returns True if t1 follows t2 chronologically (t1 is later than t2) and False otherwise



Write a boolean function named is_after that takes two Time objects, t1 and t2, and returns True if t1 follows t2 chronologically (t1 is later than t2) and False otherwise, without using if statement.
Hint: tuple comparison.