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

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


คำอธิบาย

ใช้ property DateTimeIndex.is_year_start ตรวจสอบว่าแต่ละวันที่เป็นวันที่ 1 มกราคม (วันแรกของปี) หรือไม่

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

import pandas as pd

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

print("DateTimeIndex...\n", datetimeindex)
print("\nCheck whether the date in DateTimeIndex is the first day of the year...\n", datetimeindex.is_year_start)

ผลลัพธ์

DateTimeIndex...
DatetimeIndex(['2021-12-30 02:30:50+10:30', '2021-12-31 02:30:50+10:30',
               '2022-01-01 02:30:50+10:30', '2022-01-02 02:30:50+10:30',
               '2022-01-03 02:30:50+10:30', '2022-01-04 02:30:50+10:30'],
              dtype='datetime64[ns, Australia/Adelaide]', freq='D')

Check whether the date in DateTimeIndex is the first day of the year...
[False False True False False False]

กรณีการใช้งาน

  • ตรวจสอบวันเริ่มต้นปีบัญชี/ภาษี
  • คำนวณ KPI รายปี
  • กรองข้อมูลวันที่ 1 มกราคม