【Python】文字列を日付型に変える|datetime.strftime
作成日:2025-10-06
更新日:2025-10-06

.
string 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 |
%M | 分 | 30 |
%S | 秒 | 15 |
Vocabulary
| strftime|日付を文字列に変換 |
| datetime.now|現在時刻取得 |
| Format String|書式文字列 |
| Timestamp|タイムスタンプ |
| Locale Independent|ロケール非依存 |
strftime()
isstring format time

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



2025-10-06
編集後記:
この記事の内容がベストではないかもしれません。
記事一覧
-
[Python]pathlib存在確認 【Python】フォルダとファイルの存在確認|pathlib -
[Python]Excel datapandas.DataFrame 【Python】シートにあるデータを配列に格納する|pandas.DataFrame -
[Python]Search or Scanfor Excel book 【Python】ファイル名からExcelブックを取得する|openpyxl or win32com -
[Python]Stringsplit 【Python】文字列を抜き出す|.split -
[Python]getdictionary 【Python】dictionaryから値を取得する2つの違い -
[Python]endswith+ lower 【Python】拡張子の存在確認|endswith + lower(Method Chaining)