python : strftime, strptime
본문 바로가기
▷ 도전/▷ Coding

python : strftime, strptime

by wHatsyUP 2022. 10. 1.
728x90

자주 사용하는 것은 아니지만, 은근히 필요한 경우가 많음.

그래서 할때마다 문법이 헷갈림.

물론 할 때마다 검색해서 해도 되지만 이번 기회에 정리 해봄.


 datetime  문자열로 변환

from datetime import datetime

now = datetime.now()

# 년-월-일 
date_str = now.strftime("%Y-%m-%d")

# 년-월-일 시:분:초
now_str = now.strftime("%Y-%m-%d %H:%M:%S")

print(date_str)
print(now_str)
print(type(now_str))



# output --> 2022-10-01
# output --> 2022-10-01 22:32:12
# output --> <class 'str'>

 

문자열datetime로 변환

from datetime import datetime

now_str = '2022-10-01 22:32:12'
now = datetime.strptime(now_str, "%Y-%m-%d %H:%M:%S")

print(now)
print(type(now))



# output --> 2022-10-01 22:32:12
# output --> <class 'datetime.datetime'>

 

timestamp datetime로 변환

from datetime import datetime

ts = 1664631132
now = datetime.fromtimestamp(ts)

print(now)
print(type(now))



# output --> 2022-10-01 22:32:12
# output --> <class 'datetime.datetime'>
728x90

댓글