2025.10.21(火) / 18:23

【Python】strptime

ID
34482
Published
2025-10-21 18:23
Modified
2025-10-21 18:23
Author
khiro
Categories
デフォルト
Tags

Pythonのstrptimeについて見ていこう。

文字列をdatetime型に変換する

datetime.strptime()は、文字列を日時オブジェクトに変換する。

string perse time

文字列を時刻として解析するという意味がある。

サンプルコード

strptime · ki-hi-ro/python@1cbd8ce

from datetime import datetime

date_string = "2024-06-15 14:30:00"

date_format = "%Y-%m-%d %H:%M:%S" 
parsed_date = datetime.strptime(date_string, date_format)

print("original date and time:", date_string)
print(type(date_string))

print("Parsed date and time:", parsed_date)
print(type(parsed_date))

出力結果

original date and time: 2024-06-15 14:30:00
<class 'str'>
Parsed date and time: 2024-06-15 14:30:00
<class 'datetime.datetime'>