Reputation: 127
I have the following dataframe df:
TimeStamp
2021-03-21 09:16:33
2021-03-21 09:17:06
2021-03-21 09:19:19
2021-04-13 12:20:32
2021-04-13 12:20:39
I want to filter the dataframe to only obtain the transactions from the past 36 hours; I tried the following code but I have always found dealing with timestamps troublesome.
import pandas as pd
from datetime import datetime
df = pd.read_excel(input_path)
now = datetime.now()
temp = df[now-df['TimeStamp'].astype('timedelta64[h]').iloc[-1] >= 24]
Therefore the end result is:
TimeStamp
2021-04-13 12:20:32
2021-04-13 12:20:39
Thank you
Upvotes: 1
Views: 818
Reputation: 41327
Make sure TimeStamp
is converted to_datetime()
and then use pd.Timedelta(hours=36)
:
df.TimeStamp = pd.to_datetime(TimeStamp)
df[df.TimeStamp > (now - pd.Timedelta(hours=36))]
Alternatively you can load the excel with parse_dates
so you don't have to manually convert to datetime: df = pd.read_excel(input_path, parse_dates=['TimeStamp'])
Upvotes: 2