라일락 꽃이 피는 날

[Python] strftime, strptime 본문

프로그래밍/Python

[Python] strftime, strptime

eunki 2021. 6. 14. 18:35
728x90

strftime

주어진 형식에 따라 날짜 데이터를 문자열로 반환한다.

 

%Y 연도 (4자리) ex) 2021년 → 2021
%y 연도 (2자리) ex) 2021년 → 21
%m 월 (숫자) ex) 1월 → 01
%d ex) 15일 → 15
%H 시 (24시간) ex) 오후 5시 → 17
%I 시 (12시간) ex) 오후 5시 → 5
%M ex) 8분 → 08
%S ex) 24초 → 24
%A 요일 ex) 월요일 → Monday
%a 요일 (축약) ex) 월요일 → Mon
%B 월 (문자) ex) 1월 → January
%b 월 (축약) ex) 1월 → Jan

 

import datetime

dt_now = datetime.datetime.now()
d_today = datetime.date.today()

print(dt_now.strftime('%Y-%m-%d %H:%M:%S'))  # 2021-06-16 17:10:24

print(d_today.strftime('%y/%m/%d'))  # 21/06/16

print(d_today.strftime('%A, %B %d, %Y'))  # Wednesday, June 16, 2021

print(d_today.strftime('%a, %b %d, %Y'))  # Wed, Jun 16, 2021

 

 

 

strptime

주어진 형식에 따라 문자열을 datetime 형식으로 변환한다.

from datetime import datetime

dt_string = '2021-06-16 17:10:24'

print(datetime.strptime(dt_string, '%Y-%m-%d %H:%M:%S') )  # 2021-06-16 17:10:24
dt_string = '21/06/16'

print(datetime.strptime(dt_string, '%y/%m/%d') )  # 2021-06-16 00:00:00
dt_string = 'Wednesday, June 16, 2021'

print(datetime.strptime(dt_string, '%A, %B %d, %Y') )  # 2021-06-16 00:00:00
728x90

'프로그래밍 > Python' 카테고리의 다른 글

[Python] Package, Module  (0) 2021.06.15
[Python] fileopen  (0) 2021.06.15
[Python] Comprehension (함축)  (0) 2021.06.14
[Python] Packing, Unpacking  (0) 2021.06.14
[Python] 람다 함수 (lambda function)  (0) 2021.06.04