开发者

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 pa开发者_开发知识库rticular 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜