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

Python Pandas - 날짜 형식으로 지정된 형식화된 문자열의 인덱스 반환

<시간/>

날짜 형식으로 지정된 형식이 지정된 문자열의 인덱스를 반환하려면 DateTimeIndex.strftime()을 사용하세요. Pandas의 메소드

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

import pandas as pd

기간이 7이고 빈도가 D 즉, 일 −

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

DateTimeIndex 표시 -

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

형식화됨 -

print("\nFormat with different directives...\n",
datetimeindex.strftime('%b. %d, %Y was a %A'))

예시

다음은 코드입니다 -

import pandas as pd

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

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

# display DateTimeIndex frequency
print("\nDateTimeIndex frequency...\n", datetimeindex.freq)
# display the result
print("\nFormat with different directives...\n",
datetimeindex.strftime('%b. %d, %Y was a %A'))

출력

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

DateTimeIndex...
DatetimeIndex(['2021-10-30 02:30:50+10:30', '2021-11-01 02:30:50+10:30',
'2021-11-03 02:30:50+10:30', '2021-11-05 02:30:50+10:30',
'2021-11-07 02:30:50+10:30', '2021-11-09 02:30:50+10:30',
'2021-11-11 02:30:50+10:30'],
dtype='datetime64[ns, Australia/Adelaide]', freq='2D')

DateTimeIndex frequency...
<2 * Days>

Format with different directives...
Index(['Oct. 30, 2021 was a Saturday', 'Nov. 01, 2021 was a Monday',
'Nov. 03, 2021 was a Wednesday', 'Nov. 05, 2021 was a Friday',
'Nov. 07, 2021 was a Sunday', 'Nov. 09, 2021 was a Tuesday',
'Nov. 11, 2021 was a Thursday'],
dtype='object')