เพื่อปัดเศษ Timedelta ด้วยความละเอียดที่ระบุ ให้ใช้เมธอด timestamp.round() ตั้งค่าความละเอียดความถี่รายชั่วโมง (hourly frequency) ผ่านพารามิเตอร์ freq со значением H
เริ่มต้นด้วยการนำเข้าไลบรารีที่จำเป็น:
import pandas as pd
TimeDeltas เป็นไลบรารี datetime มาตรฐานของ Python ใช้การแทนค่าที่ต่างกัน สร้าง Timedelta object
timedelta = pd.Timedelta('2 days 10 hours 45 min 20 s 35 ms 55 ns')
แสดง Timedelta
print("Timedelta...\n", timedelta)
คืนค่า Timestamp ที่ปัดเศษแล้วด้วยความถี่รายชั่วโมง ที่นี่ความละเอียดที่ระบุตั้งค่าผ่านพารามิเตอร์ "freq"
timedelta.round(freq='H')
ตัวอย่างโค้ดเต็ม
import pandas as pd
# TimeDeltas is Python's standard datetime library uses a different representation timedelta's
# create a Timedelta object
timedelta = pd.Timedelta('2 days 10 hours 45 min 20 s 35 ms 55 ns')
# display the Timedelta
print("Timedelta...\n", timedelta)
# return the rounded Timestamp
# with hourly frequency
# Here, the specified resolution is set using the "freq" parameter
res = timedelta.round(freq='H')
# display the rounded Timestamp
print("\nTimedelta (hourly rounded)...\n", res)
เอาต์พุต
จะได้ผลลัพธ์ดังนี้:
Timedelta... 2 days 10:45:20.035000055 Timedelta (hourly rounded)... 2 days 11:00:00