16.1: Time

Think Python 2ed. · LibreTexts

0%

Contents

    Text

    Size
    100%
    Theme
    Typeface
    Line length
    Spacing

    From LibreTexts, under CC BY-NC 3.0, as the source states it; its equations are written in TeX, which the PDF shows typeset. This page at LibreTexts.

    16.1: Time

    As another example of a programmer-defined type, we’ll define a class called Time that records the time of day. The class definition looks like this:

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

    We can create a new Time object and assign attributes for hours, minutes, and seconds:

    time = Time()
    time.hour = 11
    time.minute = 59
    time.second = 30
    

    The state diagram for the Time object looks like Figure \(\PageIndex{1}\).

    As an exercise, write a function called print_time that takes a Time object and prints it in the form hour:minute:second. Hint: the format sequence '%.2d' prints an integer using at least two digits, including a leading zero if necessary.

    Write a boolean function called is_after that takes two Time objects, t1 and t2, and returns True if t1 follows t2 chronologically and False otherwise. Challenge: don’t use an if statement.

    Object diagram.
    Figure \(\PageIndex{1}\): Object diagram.

    This page titled 16.1: Time was last modified on Tue, 01 Dec 2020 03:30:45 GMT and is shared under a CC BY-NC 3.0 license and was authored, remixed, and/or curated by Allen B. Downey (Green Tea Press) via source content that was edited to the style and standards of the LibreTexts platform.