Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to filter a Pandas dataframe by timestamp functon using .query()

I am trying to filter a Pandas df by dates (today and yesterday). For automation purposes I wish to filter using a timestamp function. This is pretty seamless in R:

df %>% 
  filter(date >= today() - 1)

However, my attempts to replicate in Pandas are not reaching any success so far: Yesterday comes out fine, but .query() doesnt recognise it?

yesterday = (date.today() - timedelta(days=6)).strftime('%Y-%m-%d')
df.\
   query('date >= yesterday')

Ideally I am seeking something all encompassing like:

df.\
   query('date >= (date.today() - timedelta(days=6)).strftime('%Y-%m-%d')')
like image 491
Robert Chestnutt Avatar asked Jan 01 '23 05:01

Robert Chestnutt


1 Answers

Try: df.query('date >= @yesterday'). You need @ so pandas recognizes it's a variable.

like image 115
Ugurite Avatar answered Jan 05 '23 17:01

Ugurite