[Python] Converting Strings to Time Objects and Formatting

This article explains how to read “time information” from CSV data or log files, convert it into a time object that can be handled programmatically, and conversely, format it for display.

We will implement code that simulates a system managing a factory’s start-of-work chime, converting a string read from a configuration file.

目次

Implementation Example: Reading and Formatting Start Time

We will parse the string "08-30-00" passed as configuration data, convert it into a time object, and then reformat it into a string like "08:30:00" for a bulletin board display.

Source Code

from datetime import datetime, time

# --- 1. Converting String to time Object ---
# Start time read from a configuration file (string)
# Expected format: "Hour-Minute-Second"
setting_value = "08-30-00"

# Use datetime.strptime(string, format) to parse into a datetime object first
# %H: Hour (24-hour), %M: Minute, %S: Second
# We use hyphens for the separator to match the input string
parsed_dt = datetime.strptime(setting_value, "%H-%M-%S")

# Use the .time() method to discard the date part (default 1900-01-01)
# and extract only the pure "time data"
start_time = parsed_dt.time()

print(f"Converted Type : {type(start_time)}")
print(f"Time Data      : {start_time}")

print("-" * 30)

# --- 2. Converting time Object to Display String ---
# Use strftime(format) to format it into a human-readable style
# Here, we convert it to a standard colon-separated format
display_text = start_time.strftime("%H:%M:%S")

print(f"Display String : {display_text}")
print(f"Output Type    : {type(display_text)}")

Execution Result

Converted Type : <class 'datetime.time'>
Time Data      : 08:30:00
------------------------------
Display String : 08:30:00
Output Type    : <class 'str'>

Explanation

String → time (datetime.strptime().time())

In Python’s standard library, there is no direct function to convert a string immediately into a time object. Therefore, we follow this two-step process:

  1. datetime.strptime(string, format): Converts the string into a datetime object (containing both “date + time”). During this process, a default date (usually January 1, 1900) is automatically added.
  2. .time(): Extracts only the time portion from the datetime object. This removes the unnecessary date information.

time → String (strftime)

By using the strftime() method of the time object, you can convert the time into a string with any desired format.

Syntax: time_object.strftime(format)

Common Format Specifiers:

  • %H: Hour (00-23)
  • %M: Minute (00-59)
  • %S: Second (00-59)
  • %p: AM/PM (Used in combination with %I for 12-hour clock)
よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

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

目次