LoginSignup
0
3

More than 1 year has passed since last update.

Pythonで文字列を日付に変換

Posted at

文字列から日付(datetime)に変換

from datetime import datetime

str = '20210808134937'
date = datetime.strptime(str, '%Y%m%d%H%M%S')

print(date) # 2021-08-08 13:49:37
print(type(date)) # <class 'datetime.datetime'>

文字列から日付(date)に変換

import datetime

str = '20210808134937'
date = datetime.datetime.strptime(str, '%Y%m%d%H%M%S')
tdate = datetime.date(date.year, date.month, date.day)

print(tdate) # 2021-08-08
print(type(tdate)) # <class 'datetime.date'>

日付から文字列に変換

import datetime

tdatetime = datetime.now()
tstr = tdatetime.strftime('%Y/%m/%d %H:%M:%S')

print(tstr) # 2021/08/11 17:18:51
print(type(tstr)) # <class 'str'>

日付フォーマット

書式 説明
%Y 年 西暦4桁(例、2021)
%y 年 西暦2桁(例、21)
%m 月2桁(例、12)
%d 日2桁(例、31)
%H 時 24時間表記(例、14)
%I 時 12時間表記(例、02)
%p AM、PM
%M 分2桁
%S 秒2桁
%f マイクロ秒6桁
0
3
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
3