[Python(파이썬)] : 일자와 시간(dt) 처리법 /dt., pandas

김대현·2024년 6월 21일
0

▶ 사용목적

  • Pandas를 이용하여 일자와 시간을 처리하는 방법이 존재하는데 Pandas에서 지원하는 일자시간타입(datetime64) 데이터를 이용하여 여러 일자시간타입 데이터를 한꺼번에 다룰 수 있다.



예제 데이터

# 예제 데이터 
df = pd.DataFrame({'Birth':['2019-01-01 09:10:00',
                            '2019-01-08 09:20:30',
                            '2019-02-01 10:20:00',
                            '2019-02-02 11:40:50',
                            '2019-02-28 15:10:20',
                            '2019-04-10 19:20:50',
                            '2019-06-30 21:20:50',
                            '2019-07-20 23:30:59']})
                            
# object 타입을 datetime64[ns] 타입으로 바꾼뒤 `Birth` 데이터 프레임을 새로 생성한다.
df['Birth'] = pd.to_datetime(df['Birth'], format='%Y-%m-%d %H:%M:%S', errors='raise')

연, 월, 일, 시, 분, 초 속성

df['Birth_date']       = df['Birth'].dt.date         # YYYY-MM-DD(문자)
df['Birth_year']       = df['Birth'].dt.year         # 연(4자리숫자)
df['Birth_month']      = df['Birth'].dt.month        # 월(숫자)
df['Birth_month_name'] = df['Birth'].dt.month_name() # 월(문자)

df['Birth_day']        = df['Birth'].dt.day          # 일(숫자)
df['Birth_time']       = df['Birth'].dt.time         # HH:MM:SS(문자)
df['Birth_hour']       = df['Birth'].dt.hour         # 시(숫자)
df['Birth_minute']     = df['Birth'].dt.minute       # 분(숫자)
df['Birth_second']     = df['Birth'].dt.second       # 초(숫자)
  • 연, 월, 일, 시, 분, 초 속성들 이다. 반환형태가 문자와 숫자로 상이하다.

시간 데이터를 주기(period) 단위 변환 속성

  • to_period 메서드의 인수로는 다양한 주기 문자열이 들어갈 수 있으며, 이를 통해 원하는 주기로 변환할 수 있다.
# to_period 메서드를 사용하여 다양한 주기로 변환
df['Period_Year']       = df.Yr_Mo_Dy.dt.to_period('A')   # 연 단위, 형식: 	YYYY
df['Period_Quarter']    = df.Yr_Mo_Dy.dt.to_period('Q')   # 분기 단위, 형식: YYYYQn
df['Period_Month']      = df.Yr_Mo_Dy.dt.to_period('M')   # 월 단위, 형식: 	YYYY-MM
df['Period_Week']       = df.Yr_Mo_Dy.dt.to_period('W')   # 주 단위, 형식: 	YYYY-WW
df['Period_Day']        = df.Yr_Mo_Dy.dt.to_period('D')   # 일 단위, 형식: 	YYYY-MM-DD
df['Period_Hour']       = df.Yr_Mo_Dy.dt.to_period('H')   # 시간 단위, 형식: YYYY-MM-DD HH
df['Period_Minute']     = df.Yr_Mo_Dy.dt.to_period('T')   # 분 단위, 형식: 	YYYY-MM-DD HH:MM
df['Period_Second']     = df.Yr_Mo_Dy.dt.to_period('S')   # 초 단위, 형식: 	YYYY-MM-DD HH:MM:SS
  • 연, 월, 일, 시, 분, 초 속성들 이다. 반환형태가 문자와 숫자로 상이하다.

일자관련 값 속성

df['Birth_quarter']       = df['Birth'].dt.quarter       # 분기(숫자)
df['Birth_weekday_name']  = df['Birth'].dt.day_name  	 # 요일이름(문자) (=day_name())
df['Birth_weekday']       = df['Birth'].dt.weekday       # 요일숫자(0-월, 1-화) (=dayofweek)
df['Birth_weekofyear']    = df['Birth'].dt.weekofyear    # 연 기준 몇주째(숫자) (=week)
df['Birth_dayofyear']     = df['Birth'].dt.dayofyear     # 연 기준 몇일째(숫자)
df['Birth_days_in_month'] = df['Birth'].dt.days_in_month # 월 일수(숫자) (=daysinmonth)
  • 일자관련 값들이다. 분기, 요일, 연기준 몇 일인지 몇 주인지, 해당 월의 일수는 얼마인지 알수 있다.

년, 월, 분기 의 시작과 마지막 관련 출력 속성

df['Birth_is_leap_year']     = df['Birth'].dt.is_leap_year     # 윤년 여부
df['Birth_is_month_start']   = df['Birth'].dt.is_month_start   # 월 시작일 여부
df['Birth_is_month_end']     = df['Birth'].dt.is_month_end     # 월 마지막일 여부
df['Birth_is_quarter_start'] = df['Birth'].dt.is_quarter_start # 분기 시작일 여부
df['Birth_is_quarter_end']   = df['Birth'].dt.is_quarter_end   # 분기 마지막일 여부
df['Birth_is_year_start']    = df['Birth'].dt.is_year_start    # 연 시작일 여부
df['Birth_is_year_end']      = df['Birth'].dt.is_year_end      # 연 마지막일 여부
  • 위는 윤년, 월시작, 월마지막, 분기시작, 마지막, 연시작, 마지막 여부와 관련된 속성이다.

참고자료

https://blog.naver.com/wideeyed/221603462366

profile
데이터 분석 스쿨 블로그 입니다.

0개의 댓글