Python Pandas - 表明 DateTimeIndex 中的日期是否屬於閏年


要檢查 DateTimeIndex 中的日期是否屬於閏年,請使用 DateTimeIndex.is_leap_year 屬性

首先,匯入所需的庫 -

import pandas as pd

使用週期 6 和頻率作為 Y(即年)建立 DatetimeIndex -

datetimeindex = pd.date_range('2021-12-30 02:30:50', periods=6, tz='Australia/Adelaide', freq='3Y')

顯示 DateTimeIndex -

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

檢查 DateTimeIndex 中的日期是否屬於閏年 -

print("\nCheck whether the date in DateTimeIndex belongs to a leap year or not...\n",
datetimeindex.is_leap_year)

例項

以下為程式碼 -

import pandas as pd

# DatetimeIndex with period 6 and frequency as Y i.e. years
# The timezone is Australia/Adelaide
datetimeindex = pd.date_range('2021-12-30 02:30:50', periods=6, tz='Australia/Adelaide', freq='3Y')

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

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

# Check whether the date in DateTimeIndex is a leap year or not
print("\nCheck whether the date in DateTimeIndex belongs to a leap year or not...\n",
datetimeindex.is_leap_year)

輸出

這將生成以下程式碼 -

DateTimeIndex...
DatetimeIndex(['2021-12-31 02:30:50+10:30', '2024-12-31 02:30:50+10:30',
'2027-12-31 02:30:50+10:30', '2030-12-31 02:30:50+10:30',
'2033-12-31 02:30:50+10:30', '2036-12-31 02:30:50+10:30'],
dtype='datetime64[ns, Australia/Adelaide]', freq='3A-DEC')
DateTimeIndex frequency...
<3 * YearEnds: month=12>

Check whether the date in DateTimeIndex belongs to a leap year or not...
[False True False False False True]

更新於: 18-Oct-2021

132 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告