Python Pandas - 使用每日頻率舍入 Timedelta


要使用指定的精度舍入 Timedelta,可以使用 timestamp.round() 方法。使用值 'D' 設定使用 freq 引數的每日頻率精度。

首先,匯入所需的庫 −

import pandas as pd

TimeDeltas 是 Python 的標準 datetime 庫,它使用不同的表示形式 timedelta。建立一個 Timedelta 物件 −

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

顯示 Timedelta −

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

返回具有每日頻率的舍入時間戳。在此,使用 "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

更新日期:2021 年 10 月 14 日

155 次瀏覽

開啟你的職業生涯

完成課程以獲得認證

開始
廣告
© . All rights reserved.