Computer >> 컴퓨터 >  >> 프로그램 작성 >> Python

Python Pandas - DateTimeIndex에서 시간을 자정으로 변환

<시간/>

DateTimeIndex에서 시간을 자정으로 변환하려면 DateTimeIndex.normalize()를 사용하세요. 판다에서.

먼저 필요한 라이브러리를 가져옵니다 -

import pandas as pd

기간이 7이고 빈도가 H, 즉 시간 −

인 DatetimeIndex를 만듭니다.
datetimeindex = pd.date_range('2021-10-30 02:30:50', periods=7, tz='Australia/Adelaide', freq='10H')

DateTimeIndex 표시 -

print("DateTimeIndex...\n", datetimeindex)

날짜-시간의 시간 구성 요소는 자정(예:00:00:00 -

)으로 변환됩니다.
print("\nNormalize (converted the time component to midnight)...\n",
datetimeindex.normalize())

예시

다음은 코드입니다 -

import pandas as pd

# DatetimeIndex with period 7 and frequency as H i.e. hours
# The timezone is Australia/Adelaide
datetimeindex = pd.date_range('2021-10-30 02:30:50', periods=7, tz='Australia/Adelaide', freq='10H')

# display DateTimeIndex
print("DateTimeIndex...\n", datetimeindex)

# display DateTimeIndex frequency
print("\nDateTimeIndex frequency...\n", datetimeindex.freq)

# The time component of the date-time is converted to midnight i.e. 00:00:00
print("\nNormalize (converted the time component to midnight)...\n",
datetimeindex.normalize())

출력

이것은 다음 코드를 생성합니다 -

DateTimeIndex...
DatetimeIndex(['2021-10-30 02:30:50+10:30', '2021-10-30 12:30:50+10:30',
'2021-10-30 22:30:50+10:30', '2021-10-31 08:30:50+10:30',
'2021-10-31 18:30:50+10:30', '2021-11-01 04:30:50+10:30',
'2021-11-01 14:30:50+10:30'],
dtype='datetime64[ns, Australia/Adelaide]', freq='10H')
DateTimeIndex frequency...
<10 * Hours>

Normalize (converted the time component to midnight)...
DatetimeIndex(['2021-10-30 00:00:00+10:30', '2021-10-30 00:00:00+10:30',
'2021-10-30 00:00:00+10:30', '2021-10-31 00:00:00+10:30',
'2021-10-31 00:00:00+10:30', '2021-11-01 00:00:00+10:30',
'2021-11-01 00:00:00+10:30'],
dtype='datetime64[ns, Australia/Adelaide]', freq=None)