Python 기초 - 날짜 다루기

 

간단한 날짜 다루는 방법입니다. datetime 라이브러리를 사용합니다.

 

now: 현재 날짜, 시간을 가져옵니다.

strftime: 날짜 데이터를 문자로 변형합니다.

strpime: 문자 데이터를 날짜로 변형합니다.

 

strftime과 strptime에서 사용하는 패턴은 아래와 같습니다(대소문자를 구분합니다.)

  • %Y: 네 자리 년도를 표시합니다.
  • %m: 두 자리 월을 표시합니다.
  • %d: 두 자리 일자를 표시합니다.
  • %H: 두 자리 시간, 24시간입니다.
  • %M: 두 자리 분(Minute)
  • %S: 두 자리 초(Sec)

 

timedelta: 시간을 더하거나 빼기 위해 사용합니다.

  • weeks나 days를 사용할 수 있습니다.

 

아래는 날짜를 처리하는 다양한 예제입니다.

from datetime import datetime, timedelta

print('')
print('-----------------------------------------------')
print('1. 현재 날짜와 시간을 출력합니다. 자료형(type)을 확인합니다.')
now_dt = datetime.now()
print(now_dt, type(now_dt))

print('')
print('-----------------------------------------------')
print('2. 현재 날짜와 시간을 문자로 변경(strftime)합니다. 자료형(type)을 확인합니다.')
str_now_dt = datetime.now().strftime('%Y%m%d %H:%M:%S')
print(str_now_dt, type(str_now_dt))

print('')
print('-----------------------------------------------')
print('3. 현재 날짜와 시간을 문자로 변경합니다. 시간은 제외합니다.')
str_now_d = datetime.now().strftime('%Y%m%d')
print(str_now_d, type(str_now_d))

print('')
print('-----------------------------------------------')
print('4. 현재에 3일전과 3일후를 계산(timedelta)합니다. 자료형(type)을 확인합니다.')
now_dt = datetime.now()
before_dt = now_dt - timedelta(days=3)
after_dt = now_dt + timedelta(days=3)
print('3일전:',before_dt)
print('지금:',now_dt)
print('3일후:',after_dt)

print('')
print('-----------------------------------------------')
print('5. 문자형 데이터를 날짜로 변경(strptime)합니다.')
now_d = '20221124'
now_dt = datetime.strptime(now_d,'%Y%m%d')
print(now_dt, type(now_dt))

 

+ Recent posts