Django lookups for specific hour and minutes - django

As far as I know, django does have lookups only for year, month and day. I am looking for something is equivalent to this code to get specific hour range for every Sunday for example: Every Sunday 10:50-12:35:
Entry.objects.filter(Record_Date__week_day=1,)
Record_Date__hour__gte=10)
Record_Date__hour__lte=12)
Record_Date__minute__gte=50)
Record_Date__minute__lte=35)
Do you have any idea for an alternative to do that?

__hour and __minute do not exist in django, yet your code would not be valid as 11:00 would be excluded.
I guess you will have to deal with __regex or raw SQL.

You could also just make two datetime objects, and filter(Record_Date__gte=start_datetime, Record_Date__lte=end_datetime).
It is confusing that Django doesn't choke, is Record_Date a ForeignKey to a model that has fields "minute", "hour" and "week_day" ?

Related

django - get first record for each day

I have a model Sales with:
Saler
Product sold
Date
I would like to get the first sale for each date and for each saler, how can I do that?
Thanks
Considering the model Posted in the question, the Django ORM query will be:
first_sale = Sales.objects.order_by("Saler", "Date").distinct("Saler")
Not tested, but I would try (I assumed the field for the date of the sale is named sale_date, and is of type Datetime):
first_sale = Sales.objects.filter(saler=the_saler, sale_date__date=datetime.date(2021, 05, 19)).order_by('sale_date').first()
filter will restrict the search to a given saler (the_saler), and to a given day (see the __date expression: https://docs.djangoproject.com/fr/3.1/ref/models/querysets/#date)
order_by and first will give you the first of the day.

Django-Postgres: how to group by DATE a datetime field with timezone enabled

I am having this problem with prostgresql and django:
I have a lot of events that were created on a certain date at a certain time which is stored in a datetime field created .
I want to have aggregations based on the date part of the created field. The simplest examples is: how many event are in each day of this month?.
The created field is timezone aware. So the result should change depending on the timezone the user is in. For example if you created 2 events at 23:30 UTC time on 2017-10-02 if you view them from UTC-1 you should see them on 3rd of October at 00:30 and the totals should add for the 3rd.
I am struggling to find a solution to this problem that works with a lot of data. So doing for each day and SQL statement is not an option. I want something that translates into:
SELECT count(*) from table GROUP BY date
Now I found a solution for the first part of the problem:
from django.db import connection
truncate_date = connection.ops.date_trunc_sql('day', 'created')
queryset = queryset.extra({'day': truncate_date})
total_list = list(queryset.values('day').annotate(amount=Count('id')).order_by('day'))
Is there a way to add to this the timezone that should be used by the date_trunc_sql function to calculate the day? Or some other function before date_trunc_sql and then chain that one.
Thanks!
You're probably looking for this: timezone aware date_trunc function
However bear in mind this might conflict with how your django is configured. https://docs.djangoproject.com/en/1.11/topics/i18n/timezones/
Django 2.2+ supports the TruncDate database function with timezones
You can now do the following to :
import pytz
east_coast = pytz.timezone('America/New_York')
queryset.annotate(created_date=TruncDay("created", tzinfo=east_coast))
.values("created_date")
.order_by("created_date")
.annotate(count=Count("created_date"))
.order_by("-created_date")

how to extract date from a datetime field inside a filter in django

I have used this query in my view..
temp2=transaction.objects.filter(user_id=client_obj,Date_of_trans.date()=rec_var1)[0].Trans_Amount
I need to compare a datetime field present in my model named Date_of_trans to a variable received from user but the code is not working... what query should be written?
This is basically a sql query. So you should think like that. How can you do this in sql. I mean what condition will you apply in sql. For finding records of particular date with datetime field you should check records between start of the day to end of the day.
try this
from datetime import datetime, time
temp2=transaction.objects.filter(user_id=client_obj,Date_of_trans>datetime.combine(rec_var1, time(0,0,0)), Date_of_trans <= datetime.combine(rec_var1, time(23,59,59)) )[0].Trans_Amount
The above code is written taking into consideration that rec_var1 is a date() object.
Here you check all transactions between start of the day, till end of the day. I think this will resolve your problem.
I've use datetime.combine function which combines date and time object to form datetime object which is required here.
Thanks

Get daily counts of objects from Django

I have a Django model with a created timestamp and I'd like to get the counts of objects created on each day. I was hoping to use the aggregation functionality in Django but I can't figure out how to solve my problem with it. Assuming that doesn't work I can always fall back to just getting all of the dates with values_list but I'd prefer to give the work to Django or the DB. How would you do it?
Alex pointed to the right answer in the comment:
Count number of records by date in Django
Credit goes to ara818
Guidoism.objects.extra({'created':"date(created)"}).values('created').annotate(created_count=Count('id'))
from django.db.models import Count
Guidoism.objects \
# get specific dates (not hours for example) and store in "created"
.extra({'created':"date(created)"})
# get a values list of only "created" defined earlier
.values('created')
# annotate each day by Count of Guidoism objects
.annotate(created_count=Count('id'))
I learn new tricks every day reading stack.. awesome!
Use the count method:
YourModel.objects.filter(published_on=datetime.date(2011, 4, 1)).count()

Django get unique hours in a datetime field

Is there a method that I am not finding for getting the distinct hours in a DateTimeField? I essentially want the exact same thing that .dates() provides but for hours.
I should clarify that I am talking about a QuerySet method. The dates() method I am talking about is here:
http://docs.djangoproject.com/en/1.1/ref/models/querysets/#dates-field-kind-order-asc
If not, is there a recommended known solution?
Thanks.
Adding for clarification:
I have a model called Event with a DateTimeField called start_date. We need to know which hours of a particular day have an event.
Let's say that we narrow it down to a particular month:
objects = Event.objects.filter(start_date__year=2010, start_date__month=2)
Now the dates functions could give me a a list of all the days that have an event:
distinct_days = objects.dates('start_date', 'day')
What I would like is the narrow it down to a particular day, and then get a distinct list of the hours in the day that have an event.
objects = Event.objects.filter(start_date__year=2010, start_date__month=2, start_date__day=3)
distinct_hours = objects.times('start_date', 'hour') # This command doesn't exist and am wondering how to do this
Thanks.
Do you want to get the hours from a datetime object? Which .dates() do you mean?
hour = instance.yourDateTimeField.hour
Unfortunately there isn't a good way to do this at present, the best way is to use some raw SQL in conjunction with the extra() method and then call distinct().
I have created this code in order to manually do it.
hours = []
for h in objects.values('start_date'):
hours.append(h['start_date'].hour)
tempdict = {}
for x in hours:
tempdict[x] = x
hours = tempdict.values()
hours.sort()
Simple solution: hours might be stored in separate field, with unique=True.