[Django]-Django get unique hours in a datetime field

1👍

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

2👍

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

hour = instance.yourDateTimeField.hour

1👍

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

0👍

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

👤Dawid

Leave a comment