[Python] Basics of Time Data: Creating time Objects and Accessing Attributes

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), and microsecond (0-999999).
  • Relationship with Date: Since a time object 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 the datetime type 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"))
よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次