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

Python Pandas - คืน Timedelta ใหม่ที่ปัดลง (Floor) ตามความละเอียดรายวัน

เพื่อคืน Timedelta ใหม่ที่ปัดลง (floor) ตามความละเอียดที่ระบุ ให้ใช้เมธอด timedelta.floor() สำหรับความละเอียดปัดลงตามวัน ให้ตั้งค่าพารามิเตอร์ freq เป็น 'D'

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

import pandas as pd

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

timedelta = pd.Timedelta('5 days 10 min 25 s')

แสดง Timedelta

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

คืนค่า Timestamp ที่ปัดลงแล้วด้วยความละเอียดรายวัน:

timedelta.floor(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('5 days 10 min 25 s')

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

# return the floored Timestamp
# with daily floored resolution
res = timedelta.floor(freq='D')

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

เอาต์พุต

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

Timedelta... 5 days 00:10:25
Timedelta (daily floored)... 5 days 00:00:00