Creating time objects

You can instantiate time objects from the datetime class. A time object represents a time (hour, minute (required) second, microsecond (default to zero) tzinfo (default to None) fold (keyword only, default to zero).

(class) time(hour: int, minute: int, second: int, microsecond: int, tzinfo: _TzInfo | None, fold: int)

Code Example 1

import datetime

t =  datetime.time(10, 20, 5)

Code Example 2

from datetime import time

t1 = time(10, 20, 30)
t2 = time(12, 8, 9).replace(5, 3, 44)
# Return the time formatted according to ISO.
t3 = time(21, 6, 3).isoformat() + "Z"

Code Explanation
Creating Time Objects
  • t1 Creation: A time object t1 is created with the time set to 10:20:30 (10 hours, 20 minutes, and 30 seconds). This object represents a specific time of day without any relation to a date.
Modifying Time Objects
  • t2 Creation and Modification: Initially, t2 is intended to be created with the time 12:08:09. Immediately following this, there’s an attempt to modify t2 using the replace method to set the time to 5:03:44. However, this syntax is incorrect as the original t2 creation and its modification need to be done in separate statements or correctly chained; otherwise, it raises an error due to immediate incorrect chaining of methods.
Formatting Time Objects
  • t3 Creation and Formatting:
    • A time object is created with the time set to 21:06:03.
    • This time is then converted to an ISO 8601 formatted string using the isoformat() method, resulting in a string like “21:06:03”. The “Z” (Zulu time) is manually appended to this string to indicate that this time is in UTC, though without a specific datetime context, this is more of a stylistic addition.
Printing the Outputs
  • Outputs:
    • When t1 is printed, it will display “10:20:30”, showing the time in a simple, readable format.
    • Printing t2 will likely not work as intended due to the aforementioned error in modification; if corrected, it would display “05:03:44”.
    • The output for t3 will be “21:06:03Z”, showing the time formatted according to the ISO 8601 standard with an appended “Z” to imply UTC time.