Computer >> 컴퓨터 >  >> 프로그래밍 >> Python

Python Pandas date_range()로 DateTimeIndex 날짜·시간 생성하기

Pandas에서 DateTimeIndex를 활용해 날짜와 시간 데이터를 만들려면 date_range() 함수를 사용하면 됩니다. 이 함수는 시작 시점을 기준으로 지정한 개수(periods)만큼의 날짜 범위를 생성하며, 빈도(freq)와 시간대(tz)까지 함께 설정할 수 있어 시계열 데이터 분석에 매우 유용합니다.

필수 라이브러리 임포트

먼저 Pandas 라이브러리를 임포트합니다.

import pandas as pd

DateTimeIndex 생성하기

이제 date_range()를 사용해 DateTimeIndex를 만들어 보겠습니다. 아래 예제는 다음 조건으로 날짜 범위를 생성합니다.

  • 시작 시점: 2021-09-24 02:35:55
  • 생성할 날짜 개수(periods): 8개
  • 빈도(freq): M → 월(Month) 단위 마지막 날짜
  • 시간대(tz): Australia/Sydney (호주 시드니)
datetime = pd.date_range('2021-09-24 02:35:55', periods=8, tz='Australia/Sydney', freq='M')

전체 예제 코드

아래는 DateTimeIndex를 생성한 후, 요일 이름·월 이름·연도·시·분·초 등 다양한 속성을 추출하는 전체 코드입니다.

import pandas as pd

# periods=8, freq=M(월 단위), 시간대는 Australia/Sydney로 DateTimeIndex 생성
datetime = pd.date_range('2021-09-24 02:35:55', periods=8, tz='Australia/Sydney', freq='M')

# DateTimeIndex 출력
print("DateTime...\n", datetime)

# 요일 이름 가져오기
print("\nGetting the day name..\n", datetime.day_name())

# 월 이름 가져오기
print("\nGetting the month name..\n", datetime.month_name())

# 연도 가져오기
print("\nGetting the year name..\n", datetime.year)

# 시(hour) 가져오기
print("\nGetting the hour..\n", datetime.hour)

# 분(minute) 가져오기
print("\nGetting the minutes..\n", datetime.minute)

# 초(second) 가져오기
print("\nGetting the seconds..\n", datetime.second)

실행 결과

위 코드를 실행하면 다음과 같은 출력 결과를 확인할 수 있습니다.

DateTime...
DatetimeIndex(['2021-09-30 02:35:55+10:00', '2021-10-31 02:35:55+11:00',
               '2021-11-30 02:35:55+11:00', '2021-12-31 02:35:55+11:00',
               '2022-01-31 02:35:55+11:00', '2022-02-28 02:35:55+11:00',
               '2022-03-31 02:35:55+11:00', '2022-04-30 02:35:55+10:00'],
               dtype='datetime64[ns, Australia/Sydney]', freq='M')

Getting the day name..
Index(['Thursday', 'Sunday', 'Tuesday', 'Friday', 'Monday', 'Monday','Thursday', 'Saturday'],
dtype='object')

Getting the month name..
Index(['September', 'October', 'November', 'December', 'January', 'February','March', 'April'], dtype='object')

Getting the year name..
    Int64Index([2021, 2021, 2021, 2021, 2022, 2022, 2022, 2022], dtype='int64')

Getting the hour..
    Int64Index([2, 2, 2, 2, 2, 2, 2, 2], dtype='int64')

Getting the minutes..
    Int64Index([35, 35, 35, 35, 35, 35, 35, 35], dtype='int64')

Getting the seconds..
    Int64Index([55, 55, 55, 55, 55, 55, 55, 55], dtype='int64')

결과 해석

  • freq='M'은 각 월의 마지막 날짜를 기준으로 날짜를 생성합니다. 따라서 9월 24일부터 시작했음에도 첫 번째 값은 2021-09-30입니다.
  • 출력된 시간 오프셋(+10:00, +11:00)은 호주 시드니의 일광 절약 시간(DST) 적용 여부에 따라 달라집니다.
  • day_name(), month_name() 메서드로 요일과 월의 영문 이름을 손쉽게 추출할 수 있습니다.
  • .year, .hour, .minute, .second 속성을 사용하면 연도, 시, 분, 초 값을 Int64Index 형태로 얻을 수 있습니다.

이처럼 Pandas의 date_range()와 DateTimeIndex를 활용하면 시간대가 포함된 규칙적인 날짜 시퀀스를 간단하게 만들고, 다양한 날짜·시간 속성을 자유롭게 조회할 수 있습니다.