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

Python Pandas - ปัดเศษ Timedelta ด้วยความถี่รายวัน (Daily Frequency)

เพื่อปัดเศษ Timedelta ด้วยความละเอียดที่ระบุ ให้ใช้เมธอด timestamp.round() ตั้งค่าความละเอียดความถี่รายวัน (daily frequency) ผ่านพารามิเตอร์ freq со значением 'D'

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

import pandas as pd

TimeDeltas เป็นไลบรารี datetime มาตรฐานของ Python ใช้การแทนค่าที่ต่างกัน สร้าง Timedelta object:

timedelta = pd.Timedelta('2 days 11 hours 22 min 25 s 50 ms 45 ns')

แสดง Timedelta:

print("Timedelta...\n", timedelta)

คืนค่า Timestamp ที่ปัดเศษแล้วด้วยความถี่รายวัน ที่นี่ความละเอียดที่ระบุตั้งค่าผ่านพารามิเตอร์ "freq":

timedelta.round(freq='D')

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

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 11 hours 22 min 25 s 50 ms 45 ns')

# display the Timedelta
print("Timedelta...\n", timedelta)

# return the rounded Timestamp
# with daily frequency
# Here, the specified resolution is set using the "freq" parameter
res = timedelta.round(freq='D')

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

เอาต์พุต

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

Timedelta... 2 days 11:22:25.050000045
Timedelta (daily rounded)... 2 days 00:00:00