銀河鉄道

【Python】文字列を日付型に変える|datetime.strftime

サムネイル
[Python]datetimestring format time
.strftime()
string format time

strftime() |「string format time」の略

datetime オブジェクトを任意のフォーマット文字列で整形して出力できる

from datetime import datetime

# 現在時刻
now = datetime.now()

# ① 日付だけ
str_date = now.strftime("%Y/%m/%d")       # → "2025/10/06"

# ② 時刻だけ
str_time = now.strftime("%H:%M:%S")       # → "21:05:42"

# ③ 日付+時刻
str_datetime = now.strftime("%Y/%m/%d %H:%M:%S")  # → "2025/10/06 21:05:42"

print(str_date)
print(str_time)
print(str_datetime)

ファイル名やログ向け

timestamp = now.strftime("%Y%m%d_%H%M%S")
print(timestamp)   # → "20251006_210542"

型確認

strftime() の戻り値は、純粋な文字列 (str) になる。

type(str_datetime)
# → <class 'str'>

よく使うフォーマット指定子

指定子意味
%Y西暦4桁2025
%y西暦2桁25
%m月(ゼロ詰め)10
%d日(ゼロ詰め)06
%H時(24時間制)09
%M30
%S15

Vocabulary

| strftime|日付を文字列に変換 |
| datetime.now|現在時刻取得 |
| Format String|書式文字列 |
| Timestamp|タイムスタンプ |
| Locale Independent|ロケール非依存 |

strftime() is
string format time

同じ処理をPythonでも書いてみよう

著者

author
月うさぎ

編集後記:
この記事の内容がベストではないかもしれません。

記事一覧