Python time strftime() メソッド


説明

Python time strftime() 関数は、時刻をフォーマットし、読み取り可能な文字列としてローカル時刻を返します。その形式はパラメータ format によって決まります。

構文

strftime() メソッドの構文:

time.strftime(format[, t])

パラメータ

  • format -- フォーマット文字列。
  • t -- オプションのパラメータ t は struct_time オブジェクトです。

戻り値

読み取り可能な文字列で表されたローカル時刻を返します。

注記

Python の日時フォーマット記号:

  • %y 2桁の年(00-99)
  • %Y 4桁の年(000-9999)
  • %m 月(01-12)
  • %d 月内の日(0-31)
  • %H 24時間制の時(0-23)
  • %I 12時間制の時(01-12)
  • %M 分(00-59)
  • %S 秒(00-59)
  • %a ローカルの短縮曜日名
  • %A ローカルの完全な曜日名
  • %b ローカルの短縮月名
  • %B ローカルの完全な月名
  • %c ローカルの対応する日付表現と時刻表現
  • %j 年内の通算日(001-366)
  • %p ローカルの A.M. または P.M. に相当する記号
  • %U 年内の週番号(00-53)。日曜日を週の始まりとする
  • %w 曜日(0-6)。日曜日を週の始まりとする
  • %W 年内の週番号(00-53)。月曜日を週の始まりとする
  • %x ローカルの対応する日付表現
  • %X ローカルの対応する時刻表現
  • %Z 現在のタイムゾーン名
  • %% パーセント記号そのもの

例

以下の例は、strftime() 関数の使用方法を示しています:

例

#!/usr/bin/python
# -*- coding: UTF-8 -*-

# Python3.x の print と互換性を持たせるために __future__ パッケージをインポートする
# Python3.x を使用している場合は、この行のインポートを削除できます
from __future__ import print_function

from datetime import datetime


now = datetime.now() # current date and time

year = now.strftime("%Y")
print("year:", year)

month = now.strftime("%m")
print("month:", month)

day = now.strftime("%d")
print("day:", day)

time = now.strftime("%H:%M:%S")
print("time:", time)

date_time = now.strftime("%Y-%m-%d, %H:%M:%S")
print("date and time:",date_time)

上記の例の出力結果は次のとおりです:

year: 2020
month: 09
day: 25
time: 10:24:28
date and time: 2020-09-25, 10:24:28
その他の拡張