Python의 datetime.time 객체로 구성된 NumPy 배열을 반환하려면 Pandas의 DatetimeIndex.time 속성을 사용하면 됩니다. 이 속성은 타임스탬프(Timestamp)에서 날짜 정보를 제외하고 시간 부분만 추출하여 배열 형태로 제공합니다.
1단계: 라이브러리 임포트
먼저 필요한 라이브러리를 임포트합니다.
import pandas as pd
2단계: DatetimeIndex 생성
기간(periods)은 3으로, 빈도(freq)는 나노초(ns)로 설정하여 DatetimeIndex를 생성합니다. 타임존(timezone)은 호주 시드니(Australia/Sydney)로 지정합니다.
datetimeindex = pd.date_range('2021-10-20 02:30:50', periods=3, tz='Australia/Sydney', freq='ns')
3단계: DateTimeIndex 확인
생성된 DateTimeIndex를 출력하여 확인합니다.
print("DateTimeIndex...\n", datetimeindex)
4단계: 시간(time) 부분만 추출
.time 속성을 사용하면 타임존 정보 없이 타임스탬프의 시간 부분만 담긴 NumPy 배열을 얻을 수 있습니다.
print("\nThe numpy array (time part)..\n", datetimeindex.time)
전체 예제 코드
지금까지의 내용을 하나로 정리한 전체 코드는 다음과 같습니다.
import pandas as pd
# 기간 3, 빈도 나노초(ns)로 DatetimeIndex 생성
# 타임존은 Australia/Sydney로 지정
datetimeindex = pd.date_range('2021-10-20 02:30:50', periods=3, tz='Australia/Sydney', freq='ns')
# DateTimeIndex 출력
print("DateTimeIndex...\n", datetimeindex)
# 타임존 정보 없이 날짜(date) 부분만 반환
print("\nThe numpy array (date part)..\n", datetimeindex.date)
# 타임존 정보 없이 시간(time) 부분만 반환
print("\nThe numpy array (time part)..\n", datetimeindex.time)
실행 결과
위 코드를 실행하면 다음과 같은 결과가 출력됩니다.
DateTimeIndex...
DatetimeIndex([ '2021-10-20 02:30:50+11:00',
'2021-10-20 02:30:50.000000001+11:00',
'2021-10-20 02:30:50.000000002+11:00'],
dtype='datetime64[ns, Australia/Sydney]', freq='N')
The numpy array (date part)..
[datetime.date(2021, 10, 20) datetime.date(2021, 10, 20)
datetime.date(2021, 10, 20)]
The numpy array (time part)..
[datetime.time(2, 30, 50) datetime.time(2, 30, 50)
datetime.time(2, 30, 50)]