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

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

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

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

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 ที่ปัดลงแล้วด้วยความละเอียดมิลลิวินาที:

timedelta.floor(freq='ms')

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

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 floored Timestamp
# with milliseconds floored resolution
res = timedelta.floor(freq='ms')

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

เอาต์พุต

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

Timedelta... 2 days 10:45:20.035000055
Timedelta (milliseconds floored)... 2 days 10:45:20.035000