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 次浏览

开启你的 职业生涯

通过完成课程获得认证

开始
广告
© . All rights reserved.