การแปลง Timestamp เป็น Period (ความถี่รายชั่วโมง)
ใช้เมธอด timestamp.to_period(freq='H') แปลง Timestamp เป็น Period ที่ปัดเศษลงมาที่ชั่วโมง
ขั้นตอน
- นำเข้า pandas
- สร้าง Timestamp
- ใช้
to_period(freq='H')
ตัวอย่างโค้ด
import pandas as pd
# สร้าง Timestamp
timestamp = pd.Timestamp(2021, 9, 18, 11, 50, 20, 33)
# แสดง Timestamp
print("Timestamp...\n", timestamp)
# แปลงเป็น Period ความถี่รายชั่วโมง
print("\nTimestamp to Period with hourly frequency...\n", timestamp.to_period(freq='H'))
ผลลัพธ์
Timestamp... 2021-09-18 11:50:20.000033 Timestamp to Period with hourly frequency... 2021-09-18 11:00
คำอธิบาย
ความถี่ 'H' (Hourly) จะปัดเศษนาที วินาที และส่วนทศนิยมทิ้ง คงเหลือแค่ปี-เดือน-วัน ชั่วโมง