tags:

views:

200

answers:

4

Hi,

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.

+1  A: 

Do you want to get the hours from a datetime object? Which .dates() do you mean?

hour = instance.yourDateTimeField.hour
Felix Kling
+1, though do you mean datetime.datetime.hour (without the 's')? I second the question about `dates()`.
Jarret Hardie
@Jarret Hardie: Oh your are right about the 's', thank you :)
Felix Kling
I am talking about this:http://docs.djangoproject.com/en/1.1/ref/models/querysets/#dates-field-kind-order-asc
mhost
A: 

Simple solution: hours might be stored in separate field, with unique=True.

Dejw
+1  A: 

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().

Alex Gaynor
I've tried adding the following and I can't get a distinct list from it: .extra(select={'hours': 'DATE_FORMAT(start_date, "%%H")'})
mhost
You'd need to do .extra(stuff).values_list("hours", flat=True).distinct()
Alex Gaynor
Here is the end queryset (objects is already filtered down to a specific day):objects.extra(select={'hours': 'DATE_FORMAT(start_date, "%%H")'}).values_list("hours", flat=True).distinct().order_by('hours')
mhost
A: 

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()
mhost