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

Python Pandas - ปัดเศษ Timedelta ด้วยความละเอียดที่ระบุ

เพื่อปัดเศษ Timedelta ด้วยความละเอียดที่ระบุ ให้ใช้เมธอด timestamp.round() ตั้งค่าความละเอียดผ่านพารามิเตอร์ freq

เริ่มต้นด้วยการนำเข้าไลบรารีที่จำเป็น:

import pandas as pd

สร้าง 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='s')

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

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 seconds frequency
# Here, the specified resolution is set using the "freq" parameter
res = timedelta.round(freq='s')

# display the rounded Timestamp
print("\nTimedelta (seconds rounded)...\n", res)

เอาต์พุต

จะได้ผลลัพธ์ดังนี้:

Timedelta... 2 days 10:45:20.035000055
Timedelta (seconds rounded)... 2 days 10:45:20