Edamame Edamame - 1 year ago 125
Python Question

python pandas: date/time function to compute time period

I have the following working code, trying to filter in the data within 14 days of the reference date. However, I had to hard code the date:

reference_ts = "2016-09-15 00:00:00"
df1 = df[df.my_ts >= "2016-09-01 00:00:00"]

I am wondering is there any function that I can use to compute a certain time period from a reference time point? Something like the pseudo code below:

df1 = df[df.my_ts >= date_sub(reference_ts,14)]


Answer Source

you can use pd.Timedelta():

reference_ts = pd.to_datetime("2016-09-15 00:00:00")
df1 = df[df.my_ts >= reference_ts - pd.Timedelta(days=14)]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download