오늘 할 일: 끝내주게 숨쉬기

데이터 분석을 할 때 빠지면 섭섭한 자료형이 바로 날짜, 시간입니다. 고객이 행동을 하면 기록되는 웹페이지 로그라던가 초단위로 집계되는 기계의 자동화 시스템이 시간과 함께 저장되는 대표적인 데이터라고 할 수 있겠습니다. 시간, 시점과 관련한 분석을 실행하기 위해서는 파이썬에서 어떻게 날짜와 시간을 처리하는지 알아야겠죠. 본 포스팅에서는 파이썬에서 날짜와 시간을 다루는데 사용되는 datetime 라이브러리 사용방법에 대해 알아보겠습니다. 

 

datetime 라이브러리 소개

datetime은 파이썬에서 날짜와 시간을 다루는 클래스, 함수들을 모아놓은 라이브러리입니다. datetime 라이브러리는 날짜와 시간을 함께 저장하는 datetime 클래스, 날짜 정보를 저장하는 date 클래스, 시간 정보를 저장하는 time 클래스, 시차 정보를 저장하는 timedelta 클래스 등을 제공합니다.

 

현재 시간 가져오기: datetime.datetime.now()

import datetime as dt
now = dt.datetime.now()
print(now)          
print(type(now))
2021-07-25 11:21:36.742063
<class 'datetime.datetime'>

 

now 클래스 메서드는 현재 시각을 datetime 클래스 객체로 만들어 반환합니다. datetime 클래스는 저장된 시각으로부터 년, 월, 일 등 정보를 추출할 수 있는 속성을 가지는데요, 아래 예제로 확인해보겠습니다.

 

print(now.year)
print(now.month)
print(now.day)
print(now.hour)
print(now.minute)
print(now.second)
print(now.microsecond)
2021
7
25
11
21
36
742063

 

또 원하는 문자열 형식으로 반환해주는 strftime, 날짜만 추출하는 date, 시간만 추출하는 time, 요일을 추출하는 weekday 메소드를 갖고 있습니다.

 

print(now.strftime('%y-%m-%d'))
print(now.date())
print(now.time())
print(now.weekday())
21-07-25
2021-07-25
11:21:36.742063
6

 

weekday는 0인 월요일부터 시작하여 1:화, 2:수, 3:목, 4:금, 5:토, 6:일을 의미하고 있습니다. 오늘은 일요일이어서 6으로 반환되었습니다.

 

 

문자열로 날짜 만들기: datetime.datetime.strptime()

strptime 을 사용하면 날짜와 시간 정보가 저장된 문자열을 읽어 datetime 클래스 객체를 만들 수 있습니다.
다양한 포매팅 옵션을 이용해서 datetime 객체를 만들어줄 수 있는데요, 첫 번째 파라미터는 날짜와 시간 정보를 가진 문자열을, 두 번째 파라미터는 그 문자열의 숫자들이 무엇을 의미하는지를 알려주는 포맷을 입력해줍니다.

dt_str = '2021-07-25 12:34:56'
dt_sample = dt.datetime.strptime(dt_str, '%Y-%m-%d %H:%M:%S')
print(type(dt_sample))
print(dt_sample)
<class 'datetime.datetime'>
2021-07-25 12:34:56

 

strftime()에서 사용하는 자세한 포맷팅 코드는 아래 링크를 참고하세요.

 

datetime — Basic date and time types — Python 3.8.11 documentation

datetime — Basic date and time types Source code: Lib/datetime.py The datetime module supplies classes for manipulating dates and times. While date and time arithmetic is supported, the focus of the implementation is on efficient attribute extraction for

docs.python.org

 

 

시차 연산: datetime.timedelta()

timedelta를 이용하면 시간끼리의 연산이 가능합니다.

now = datetime.datetime.now()
print(now)      
 
yesterday = now - datetime.timedelta(days=1)
tomorrow = now + datetime.timedelta(days=1)
print(yesterday)
print(tomorrow)
2021-07-25 11:56:13.928199
2021-07-24 11:56:13.928199
2021-07-26 11:56:13.928199

 

timedelta에 입력할 수 있는 파라미터들은 아래와 같습니다.

  • 1주 : datetime.timedelta(weeks=1)
  • 1일 : datetime.timedelta(days=1)
  • 1시간 : datetime.timedelta(hours=1)
  • 1분 : datetime.timedelta(minutes=1)
  • 1초 : datetime.timedelta(seconds=1)
  • 1밀리초 : datetime.timedelta(milliseconds=1)
  • 1마이크로초 : datetime.timedelta(microseconds=1)

 

timedelta의 단점은 날짜와 초 단위로만 연산을 할 수 있다는 점입니다. 이를 보완하기 위해 dateutil 패키지에 있는  relativedelta 클래스를 이용할 수 있습니다.  relativedelta 클래스는 월 단위의 시차 계산을 제공합니다.

예를 들어 특정 일의 2달 후, 2달 전 날짜를 구하려면 다음과 같이 실행할 수 있습니다.

from dateutil.relativedelta import relativedelta

print(now)
print(now + relativedelta(months=2))
print(now - relativedelta(months=2))
2021-07-25 11:56:13.928199
2021-09-25 11:56:13.928199
2021-05-25 11:56:13.928199

 

참고

https://docs.python.org/3/library/datetime.html

 

datetime — Basic date and time types — Python 3.9.6 documentation

datetime — Basic date and time types Source code: Lib/datetime.py The datetime module supplies classes for manipulating dates and times. While date and time arithmetic is supported, the focus of the implementation is on efficient attribute extraction for

docs.python.org

https://docs.python.org/3.8/library/datetime.html#strftime-and-strptime-format-codes

 

datetime — Basic date and time types — Python 3.8.11 documentation

datetime — Basic date and time types Source code: Lib/datetime.py The datetime module supplies classes for manipulating dates and times. While date and time arithmetic is supported, the focus of the implementation is on efficient attribute extraction for

docs.python.org

https://datascienceschool.net/01%20python/02.15%20%ED%8C%8C%EC%9D%B4%EC%8D%AC%EC%97%90%EC%84%9C%20%EB%82%A0%EC%A7%9C%EC%99%80%20%EC%8B%9C%EA%B0%84%20%EB%8B%A4%EB%A3%A8%EA%B8%B0.html

 

2.15 파이썬에서 날짜와 시간 다루기 — 데이터 사이언스 스쿨

.ipynb .pdf to have style consistency -->

datascienceschool.net