Search code snippets, questions, articles...

Filter by current time - n hours SQLAlchemy

To filter records based on time difference in SQLAlchemy, the below code can be used.
import datetime, timedelta

n = 10
time_difference = - timedelta(hours=n)
result = session.query(User).filter(
            User.last_active_timestamp < time_difference

We are importing datetime to get the current date-time and timedelta to get the date-time of the last 10 hours. Then we are subtracting them and pass them in our filter query to get the records where last_active_timestamp is less than the time_difference.

Search Index Data (The code snippet can also be found with below search text)

Filter by time difference SQLAlchemy
Was this helpful?
Programming Feeds
Learn something new everyday on Devsheet