Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Python Pandas - Kiểm tra năm nhuận từ đối tượng Period

Để kiểm tra xem năm của đối tượng Period có phải năm nhuận hay không, sử dụng thuộc tính period.is_leap_year. Trả về True nếu là năm nhuận, ngược lại False.

Các bước thực hiện

  1. Import thư viện: import pandas as pd
  2. Tạo hai Period object:
    • period1 = pd.Period("2020-09-23 05:55:30") (2020 là năm nhuận)
    • period2 = pd.Period(freq="Y", year=2021, month=7, day=16, hour=2, minute=35) (2021 không phải năm nhuận)
  3. Truy cập period1.is_leap_year và period2.is_leap_year.

Ví dụ hoàn chỉnh

import pandas as pd

period1 = pd.Period("2020-09-23 05:55:30")
period2 = pd.Period(freq="Y", year=2021, month=7, day=16, hour=2, minute=35)

print("Period1...\n", period1)
print("Period2...\n", period2)

res1 = period1.is_leap_year
res2 = period2.is_leap_year

print("\nIs the year in the 1st Period object a leap year ...\n", res1)  # True
print("\nIs the year in the 2nd Period object a leap year ...\n", res2)   # False

Kết quả

Period1... 2020-09-23 05:55:30
Period2... 2021
Is the year in the 1st Period object a leap year ... True
Is the year in the 2nd Period object a leap year ... False