专门有Timedelta
对象表示时间差。
- 字符串
print(pd.Timedelta('2 days 2 hours 15 minutes 30 seconds'))
'''
2 days 02:15:30
'''
- 整数
print(pd.Timedelta(6, unit='h'))
'''
0 days 06:00:00
'''
- 数据偏移
例如:周,天,小时,分钟,秒,毫秒,微秒,纳秒
print(pd.Timedelta(hours=2))
'''
0 days 02:00:00
'''
运算操作
可以Series/DataFrame上直接操作,通过在datetime64[ns] Series对象或者Timestamp上减法操作来构造timedelta64[ns] Series对象。
以如下代码作为例子:
s = pd.Series(pd.date_range('2012-1-1', periods=3, freq='D'))
td = pd.Series([ pd.Timedelta(days=i) for i in range(3) ])
df = pd.DataFrame(dict(A = s, B = td))
print(df)
'''
A B
0 2012-01-01 0 days
1 2012-01-02 1 days
2 2012-01-03 2 days
'''
相加
print(df['A'] + df['B'])
'''
0 2012-01-01
1 2012-01-03
2 2012-01-05
dtype: datetime64[ns]
'''
相减
print(df['A'] - df['B'])
'''
0 2012-01-01
1 2012-01-01
2 2012-01-01
dtype: datetime64[ns]
'''