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

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

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

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

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.ceil(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 ceiled Timestamp
# with seconds ceiling resolution
res = timedelta.ceil(freq='S')

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

เอาต์พุต

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

Timedelta... 2 days 10:45:20.035000055
Timedelta (seconds ceiled)... 2 days 10:45:21