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

Python Pandas - แปลงเวลาใน DateTimeIndex เป็นเที่ยงคืน (normalize)


คำอธิบาย

ใช้เมธอด DateTimeIndex.normalize() เพื่อตั้งค่าส่วนเวลา (time component) ให้เป็นเที่ยงคืน (00:00:00) แต่คงวันที่และเขตเวลาไว้

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

import pandas as pd

# DateTimeIndex 7 รอบ ความถี่ 10 ชั่วโมง
datetimeindex = pd.date_range('2021-10-30 02:30:50', periods=7, tz='Australia/Adelaide', freq='10H')

print("DateTimeIndex...\n", datetimeindex)
print("\nNormalize (converted the time component to midnight)...\n", datetimeindex.normalize())

ผลลัพธ์

DateTimeIndex...
DatetimeIndex(['2021-10-30 02:30:50+10:30', '2021-10-30 12:30:50+10:30',
               '2021-10-30 22:30:50+10:30', '2021-10-31 08:30:50+10:30',
               '2021-10-31 18:30:50+10:30', '2021-11-01 04:30:50+10:30',
               '2021-11-01 14:30:50+10:30'], dtype='datetime64[ns, Australia/Adelaide]', freq='10H')

Normalize (converted the time component to midnight)...
DatetimeIndex(['2021-10-30 00:00:00+10:30', '2021-10-30 00:00:00+10:30',
               '2021-10-30 00:00:00+10:30', '2021-10-31 00:00:00+10:30',
               '2021-10-31 00:00:00+10:30', '2021-11-01 00:00:00+10:30',
               '2021-11-01 00:00:00+10:30'], dtype='datetime64[ns, Australia/Adelaide]', freq=None)

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

  • จัดกลุ่มข้อมูลตามวันที่ (ignore เวลา)
  • เปรียบเทียบวันที่โดยไม่สนใจส่วนเวลา
  • เตรียมข้อมูลสำหรับ resampling รายวัน