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)
import datetime
t = datetime.time(10, 20, 5)
print(t)
10:20:05
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"
print(t1)
print(t2)
print(t3)
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.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.t3
Creation and Formatting: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.t1
is printed, it will display “10:20:30”, showing the time in a simple, readable format.t2
will likely not work as intended due to the aforementioned error in modification; if corrected, it would display “05:03:44”.t3
will be “21:06:03Z”, showing the time formatted according to the ISO 8601 standard with an appended “Z” to imply UTC time.10:20:30
05:03:44
21:06:03Z