Để làm tròn xuống (floor) DateTimeIndex đến tần suất giờ, dùng DateTimeIndex.floor(freq='H').
Các bước thực hiện
1. Import thư viện
import pandas as pd
2. Tạo DateTimeIndex (tần suất 20 phút)
datetimeindex = pd.date_range(
'2021-09-29 07:20:32.261811624',
periods=5,
tz='Australia/Adelaide',
freq='20min'
)
3. Hiển thị DateTimeIndex
print("DateTimeIndex...\n", datetimeindex)
4. Floor giờ
print("\nFloor giờ...\n",
datetimeindex.floor(freq='H'))
Ví dụ hoàn chỉnh
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("\nFloor giờ...\n",
datetimeindex.floor(freq='H'))
Kết quả đầu ra
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')
Floor giờ...
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)
Giải thích
- Gốc: 07:20, 07:40, 08:00, 08:20, 08:40 (có phút/giây lẻ)
- Floor giờ: cắt bỏ phút/giây, giữ nguyên giờ
- 07:20 → 07:00
- 07:40 → 07:00
- 08:00 (có giây lẻ) → 08:00
- 08:20 → 08:00
- 08:40 → 08:00
So sánh floor/ceil/round giờ
| Gốc | floor('H') | ceil('H') | round('H') |
|---|---|---|---|
| 07:20:32 | 07:00:00 | 08:00:00 | 07:00:00 |
| 07:40:32 | 07:00:00 | 08:00:00 | 08:00:00 |
| 08:00:32 | 08:00:00 | 09:00:00 | 08:00:00 |
Ứng dụng: Resample dữ liệu theo giờ, groupby giờ, tạo báo cáo hàng giờ.