Python Pandas - 使用秒頻舍入 Timedelta


要以指定的精度舍入 Timedelta,請使用 timestamp.round() 方法。使用值 ‘s’freq 引數設定秒頻率精度。

首先,匯入必需的庫 −

import pandas as pd

建立 Timedelta 物件 −

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

顯示 Timedelta −

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

返回舍入後的時間戳,精度為秒。此處,使用 "freq" 引數設定指定的精度: −

timedelta.round(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('1 days 11 hours 22 min 25 s 50 ms 45 ns')

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

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

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

輸出

將會生成以下程式碼 −

Timedelta...
1 days 11:22:25.050000045

Timedelta (seconds rounded)...
1 days 11:22:25

更新日期: 14-Oct-2021

2K+ 瀏覽

開啟你的 職業生涯

完成課程並獲得認證

開始學習
廣告
© . All rights reserved.