Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Python Pandas - ตรวจสอบวันที่ใน DateTimeIndex เป็นปีอธิกสุรทินหรือไม่


คำอธิบาย

ใช้ property DateTimeIndex.is_leap_year ตรวจสอบว่าแต่ละวันที่ใน DateTimeIndex อยู่ในปีอธิกสุรทิน (leap year) หรือไม่ คืนค่า Boolean array

ตัวอย่างโค้ด

import pandas as pd

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

print("DateTimeIndex...\n", datetimeindex)
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', '2021-12-31 02:30:50+10:30',
               '2021-12-31 02:30:50+10:30', '2036-12-31 02:30:50+10:30'],
              dtype='datetime64[ns, Australia/Adelaide]', freq='3A-DEC')

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

ปีอธิกสุรทิน (Leap Year) คือ

  • ปีที่หาร 4 ลงตัว **แต่** ไม่หาร 100 ลงตัว → ปีอธิกสุรทิน
  • ปีที่หาร 400 ลงตัว → ปีอธิกสุรทิน (เช่น 2000, 2400)
  • 2024, 2036 เป็นปีอธิกสุรทิน → True