0

I have a PostgreSQL query in Python with data of reservations. These reservations have a date.

I would like to make a filter where the user says which interval of dates are going to be in the dataframe.

For example, I would like to have the reservations from 01-01-22 to 01-03-22.

The problem is that I don't know how to create this filter, and whether it should be in Python or in my SQL query!

My DF looks basically like this:

Date Reservation ID Route 
01-01-22 35642 LA-SD
01-02-22 12432 LA-SD
01-03-22 55652 LA-SD
01-04-22 87642 LA-SD
01-05-22 97612 LA-SD
01-06-22 09731 LA-SD
01-06-22 25876 LA-SD
01-08-22 23775 LA-SD
3
  • For Python, DataFrame.query? Commented Mar 24, 2022 at 19:13
  • Use Postgres Range type and do something like: select '01/03/2022'::date <@ daterange('01-01-2022', '01-03-2022', '[]'); t where range operators are explained here Range operators. Commented Mar 24, 2022 at 19:17
  • You can also use BETWEEN in a WHERE statement. For example: WHERE date BETWEEN '01-01-22 AND '01-03-22' w3schools.com/sql/sql_between.asp Commented Mar 24, 2022 at 19:24

1 Answer 1

2

I guess that your "Date" column is of type text. If so it has to be cast to type date first and then a simple query will do it all for you. Basically I think that data manipulation, filtering, aggregation etc. is much easier and better done with data tools, i.e. SQL. Here it is:

select * from the_table 
where to_date("Date", 'mm-dd-yy') between '2022-01-01' and '2022-01-03';

-- Parameterized:
select * from the_table 
where to_date("Date", 'mm-dd-yy') between :period_start and :period_end;
Sign up to request clarification or add additional context in comments.

1 Comment

this is the answer I wanted! Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.