Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter by timestamp in Query

Tags:

django

I have a list of Jobs. They are filtered by job_type, and complete=False/True. Ex: Job.objects.filter(job_type=1, complete=False)

How would I filter these by the timestamp of the Job like: job.timestamp.strftime(date_filter) == job.today().strftime(date_filter)

So I want to return finaly a list like this:

Job.objects.filter(
   job_type=1,
   complete=False, 
   timestamp.strftime(date_filter)=datetime.today().strftime(date_filter)
).distinct()
like image 780
Harry Avatar asked Mar 20 '26 05:03

Harry


1 Answers

If I understand you question correctly, you are trying to filter all of the Jobs that occur on a certain day? So calculate a date range, and then use that in your filter:

from datetime import datetime, timedelta
today = datetime.now().date()

if date_filter == "day":
    timestamp_from = datetime.now().date()
    timestamp_to = datetime.now().date() + timedelta(days=1)
elif date_filter == "month":
    # Etc...
elif date_filter == "year":
    # Etc...

Job.objects.filter(
    job_type = 1,
    complete = False, 
    timestamp__gte = timestamp_from,
    timestamp__lt = timestamp_to,
).distinct()

Otherwise, you might be able to do something funky using an extra SQL WHERE clause

like image 109
Humphrey Avatar answered Mar 24 '26 09:03

Humphrey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!