當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Python Pandas Timedelta構造函數用法及代碼示例


Pandas Timedelta(~)構造函數創建一個新的Timedelta對象,表示以您指定的單位表示的時間差。它通常用於執行日期算術.

例子

初始化時間增量

以下是 Pandas 提供的時間單位:

"Y", "M", "W", "D", "T", "S", "L", "U", or "N"
"days" or "day"
"hours", "hour", "hr", or "h"
"minutes", "minute", "min", or "m"
"seconds", "second", or "sec"
"milliseconds", "millisecond", "millis", or "milli"
"microseconds", "microsecond", "micros", or "micro"
"nanoseconds", "nanosecond", "nanos", "nano", or "ns".

2 天的Timedelta

pd.Timedelta("2 days")



Timedelta('2 days 00:00:00')

同樣,指定關鍵字參數:

pd.Timedelta(days=2)



Timedelta('2 days 00:00:00')

同樣,指定 units

pd.Timedelta(2, unit="days")



Timedelta('2 days 00:00:00')

2 天 5 小時的 Timedelta

pd.Timedelta("2 days 5 hours")



Timedelta('2 days 05:00:00')

同樣,指定關鍵字參數:

pd.Timedelta(days=2, hours=5)



Timedelta('2 days 05:00:00')

2 天的負麵 Timedelta

pd.Timedelta("- 2 days")



Timedelta('-2 days +00:00:00')

not-a-date Timedelta

pd.Timedelta(None)



NaT

日期算術

DatetimeIndex

考慮以下 DatetimeIndex

date_index = pd.date_range("2020-12-20","2020-12-21")
date_index



DatetimeIndex(['2020-12-20', '2020-12-21'], dtype='datetime64[ns]', freq='D')

假設我們有以下Timedelta

dt = pd.Timedelta("2 days")
dt



Timedelta('2 days 00:00:00')

dt 添加到 date_index 會應用 2 天的偏移量:

date_index + dt



DatetimeIndex(['2020-12-22', '2020-12-23'], dtype='datetime64[ns]', freq=None)

要應用 2*2 天的偏移量:

date_index + (2 * dt)



DatetimeIndex(['2020-12-24', '2020-12-25'], dtype='datetime64[ns]', freq=None)

相關用法


注:本文由純淨天空篩選整理自Isshin Inada大神的英文原創作品 Pandas | Timedelta constructor。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。