When you want to handle “time only, without date” in Python (e.g., store opening hours, alarm settings), use the time class from the datetime module.
Unlike the datetime type, the time object does not hold information about the year, month, day, or timezone (by default). It purely manages hour, minute, second, and microsecond.
This article explains how to create a time object and how to access each of its elements.
Implementation Example: Defining a Fixed Time and Getting Elements
This code example defines a specific time (12:15:05) and retrieves its components (hour, minute, second) individually.
Source Code
from datetime import time
# 1. Generate a time object by specifying a specific time
# Argument order: (hour, minute, second, microsecond)
# Seconds and microseconds are optional (default is 0)
scheduled_time = time(12, 15, 5)
print(f"Set Time (time): {scheduled_time}")
print("-" * 20)
# 2. Accessing each attribute
# Parentheses () are not needed; access via variable_name.attribute_name
print(f"Hour : {scheduled_time.hour}")
print(f"Minute : {scheduled_time.minute}")
print(f"Second : {scheduled_time.second}")
# Accessing microsecond (0 since it was not specified)
print(f"Microsecond : {scheduled_time.microsecond}")
Execution Result
Set Time (time): 12:15:05
--------------------
Hour : 12
Minute : 15
Second : 5
Microsecond : 0
Explanation
Characteristics of the time Object
- Information Held: It only holds
hour(0-23),minute(0-59),second(0-59), andmicrosecond(0-999999). - Relationship with Date: Since a
timeobject alone does not possess information about “when” (which year or month), you cannot perform calculations that cross dates (e.g., “2 hours after 23:00”) using this object alone. If you need such calculations, use thedatetimetype instead.
String Formatting
The time object also has the strftime() method, allowing you to convert it into a string of any format.
# Example: Create a string like "12:15"
print(scheduled_time.strftime("%H:%M"))
