Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get pandas Timestamp offset by certain amount of months?

Suppose I have a pandas Timestamp object t1.

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

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

like image 771
Apogentus Avatar asked Jun 24 '15 15:06

Apogentus


People also ask

How do you use date offset?

DateOffsets can be created to move dates forward a given number of valid dates. For example, Bday(2) can be added to a date to move it two business days forward. If the date does not start on a valid date, first it is moved to a valid date.

How do I add months to pandas?

In pandas, a string is converted to a datetime object using the pd. to_datetime() method and pd. DateOffset() method is used to add months to the created pandas object.


1 Answers

You can use relativedelta:

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

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

Or DateOffset:

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

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

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

pd.offsets.relativedelta since 0.20.0

like image 113
EdChum Avatar answered Oct 22 '22 12:10

EdChum