บทนำ
ใช้ DateTimeIndex.floor() พร้อม freq='H' เพื่อปัดลงเป็นหน่วยชั่วโมง
ขั้นตอน
1. นำเข้าไลบรารี
import pandas as pd
2. สร้าง DateTimeIndex ความถี่ 20 นาที
datetimeindex = pd.date_range('2021-09-29 07:20:32.261811624', periods=5, tz='Australia/Adelaide', freq='20min')
3. ดำเนินการ Floor ความถี่ชั่วโมง
print("\nPerforming floor operation with hourly frequency...\n", datetimeindex.floor(freq='H'))
ตัวอย่างโค้ดเต็ม
import pandas as pd
datetimeindex = pd.date_range('2021-09-29 07:20:32.261811624', periods=5, tz='Australia/Adelaide', freq='20min')
print("DateTimeIndex...\n", datetimeindex)
print("DateTimeIndex frequency...\n", datetimeindex.freq)
print("\nPerforming floor operation with hourly frequency...\n", datetimeindex.floor(freq='H'))
ผลลัพธ์
DateTimeIndex...
DatetimeIndex(['2021-09-29 07:20:32.261811624+09:30', '2021-09-29 07:40:32.261811624+09:30',
'2021-09-29 08:00:32.261811624+09:30', '2021-09-29 08:20:32.261811624+09:30',
'2021-09-29 08:40:32.261811624+09:30'],
dtype='datetime64[ns, Australia/Adelaide]', freq='20T')
DateTimeIndex frequency...
<20 * Minutes>
Performing floor operation with hourly frequency...
DatetimeIndex(['2021-09-29 07:00:00+09:30', '2021-09-29 07:00:00+09:30',
'2021-09-29 08:00:00+09:30', '2021-09-29 08:00:00+09:30',
'2021-09-29 08:00:00+09:30'],
dtype='datetime64[ns, Australia/Adelaide]', freq=None)
คำอธิบาย
เวลาถูกปัดลงเป็นชั่วโมงปัจจุบัน: 07:20 → 07:00, 07:40 → 07:00, 08:00:32 → 08:00, 08:20 → 08:00, 08:40 → 08:00 นาทีและวินาทีถูกรีเซ็ตเป็นศูนย์