Computer >> Computer tutorials >  >> Programming >> Python

Python Pandas - Indicate if the date from the PeriodIndex object belongs to a leap year


To indicate if the date from the PeriodIndex object belongs to a leap year, use the periodIndex.is_leap_year property.

At first, import the required libraries −

import pandas as pd

Create a PeriodIndex object −

periodIndex = pd.PeriodIndex(['2021-09-25 07:50:35', '2019-10-30 04:35:45',
'2016-07-15 02:25:15', '2020-06-25 09:20:55'], freq="T")

Display PeriodIndex object −

print("PeriodIndex...\n", periodIndex)

Check whether the date is a leap year −

print("\nWhether the date is a leap year?\n", periodIndex.is_leap_year)

Example

Following is the code −

import pandas as pd

# Create a PeriodIndex object
# PeriodIndex is an immutable ndarray holding ordinal values indicating regular periods in time
# We have set the frequency using the "freq" parameter
periodIndex = pd.PeriodIndex(['2021-09-25 07:50:35', '2019-10-30 04:35:45',
'2016-07-15 02:25:15', '2020-06-25 09:20:55'], freq="T")

# Display PeriodIndex object
print("PeriodIndex...\n", periodIndex)

# Display PeriodIndex frequency
print("\nPeriodIndex frequency object...\n", periodIndex.freq)

# Display PeriodIndex frequency as string
print("\nPeriodIndex frequency object as a string...\n", periodIndex.freqstr)

# Check whether the date is a leap year
print("\nWhether the date is a leap year?\n", periodIndex.is_leap_year)

Output

This will produce the following code −

PeriodIndex...
PeriodIndex(['2021-09-25 07:50', '2019-10-30 04:35', '2016-07-15 02:25','2020-06-25 09:20'],
dtype='period[T]')

PeriodIndex frequency object...
<Minute>

PeriodIndex frequency object as a string...
T

Whether the date is a leap year?
[False False True True]