0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Python_datetimeフォーマット

Posted at

Pythonの日時フォーマット指定子

datetime.strftime()datetime.strptime() で使用できるフォーマット指定子の一覧です。これらを使って、日時を文字列に変換したり、文字列を日時に変換したりできます。


日付に関する指定子

指定子 説明
%Y 西暦4桁 2023
%y 西暦下2桁 23
%m 月(ゼロ埋め、01~12) 01(1月)
%B 月名(英語) January
%b 月名の略称(英語) Jan
%d 日(ゼロ埋め、01~31) 05
%j 年内の通算日(001~366) 005(1月5日)
%w 曜日番号(0:日曜日~6:土曜日) 0
%A 曜日名(英語) Sunday
%a 曜日名の略称(英語) Sun

時刻に関する指定子

指定子 説明
%H 時間(24時間制、ゼロ埋め、00~23) 14
%I 時間(12時間制、ゼロ埋め、01~12) 02
%p 午前/午後(英語、ロケール依存) AM / PM
%M 分(ゼロ埋め、00~59) 30
%S 秒(ゼロ埋め、00~59) 45
%f マイクロ秒(6桁、ゼロ埋め) 123456
%Z タイムゾーン名 UTC / JST
%z UTCオフセット(±HHMM形式) +0900

その他の指定子

指定子 説明
%c ロケールに依存する日時表現 Tue Jan 3 14:30:45 2023
%x ロケールに依存する日付表現 01/03/23(英語圏)
%X ロケールに依存する時刻表現 14:30:45
%% リテラルの% %

使用例

日時を文字列に変換(strftime

from datetime import datetime

now = datetime(2023, 1, 5, 14, 30, 45)

# フォーマットを適用
formatted = now.strftime("%Y-%m-%d %H:%M:%S")
print(formatted)  # 出力: 2023-01-05 14:30:45

文字列を日時に変換(strptime

from datetime import datetime

# 日時文字列
date_string = "2023-01-05 14:30:45"

# フォーマットに基づいて変換
parsed_date = datetime.strptime(date_string, "%Y-%m-%d %H:%M:%S")
print(parsed_date)  # 出力: 2023-01-05 14:30:45

これらのフォーマット指定子を利用することで、柔軟に日付や時刻を操作できます!

0
1
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?