我怎样才能让 pandas 时间戳抵消一定的月份?

2022-01-13 00:00:00 python pandas timestamp offset

问题描述

假设我有一个 pandas Timestamp 对象 t1.

Suppose I have a pandas Timestamp object t1.

import pandas a pd
t1=pd.Timestamp('2013-04-01 00:00:00')

如何获得另一个 pandas 时间戳,从 t1 偏移 k 个月?

How can I get another pandas timestamp, offset by k months from t1?


解决方案

你可以使用relativedelta:

In [135]:
k=2
t1 + pd.datetools.relativedelta(months=k)

Out[135]:
Timestamp('2013-06-01 00:00:00')

DateOffset:

In [136]:
k=2
t1 + pd.DateOffset(months=k)

Out[136]:
Timestamp('2013-06-01 00:00:00')

感谢@AlexRiley 的建议编辑,relativedelta 已移至

Thanks to @AlexRiley for the suggested edit, relativedelta has been moved to

pd.offsets.relativedelta0.20.0

相关文章