python
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 = datetime.now() - 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.
Was this helpful?
Similar Posts