Home > Net >  Subtract/add days to Pandas Timestamp
Subtract/add days to Pandas Timestamp

Time:05-16

How do I subtract/add days (integer) to a Pandas Timestamp object?

For example, my atomics and datatypes are (lifted from Pycharm):

startDate = {Timestamp} 2008-09-20 00:00:00
dayDistance = {int} 124

The code as pulled from the Internet returns None:

from datetime import timedelta
newDate = startDate - timedelta(days=dayDistance)

I am expecting an object of type Timestamp so it is compatible with the rest of the code downstream from here.

CodePudding user response:

pandas has its own Timedelta data type:

start_date = pd.Timestamp("2008-09-20 00:00:00")
dayDistance = 124

new_date = start_date - pd.Timedelta(dayDistance, unit="d")

But Python's built-in timedelta works too:

from datetime import timedelta
new_date = start_date - timedelta(days=dayDistance)

CodePudding user response:

Actually it works fine on my test. But you may use pd.Timedelta instead

import pandas as pd
from datetime import timedelta

ts = pd.Timestamp.now()
print(f"{type(ts)} {ts}")
dt_td_ts = ts - timedelta(days=10)
pd_td_ts = ts - pd.Timedelta(10, unit='d')
print(f"With datetime timedelta: ({type(dt_td_ts)}) {dt_td_ts}")
print(f"With pandas   timedelta: ({type(pd_td_ts)}) {pd_td_ts}")

returns

<class 'pandas._libs.tslibs.timestamps.Timestamp'> 2022-05-15 22:20:04.596195
With datetime timedelta: (<class 'pandas._libs.tslibs.timestamps.Timestamp'>) 2022-05-05 22:20:04.596195
With pandas   timedelta: (<class 'pandas._libs.tslibs.timestamps.Timestamp'>) 2022-05-05 22:20:04.596195

as you can see the type is Timestamp as expected even when using datetime.timedelta

  • Related