分为两步
objs = StoreVideoEventSummary.objects.filter(Timestamp__range=(start_time, end_time), Customer__id=customer_id, Store__StoreName=store) .order_by("Timestamp")def date_hour(timestamp): return datetime.datetime.fromtimestamp(timestamp).strftime("%x %H")groups = itertools.groupby(objs, lambda x:date_hour(x.Timestamp))#since groups is an iterator and not a list you have not yet traversed the listfor group,matches in groups: #now you are traversing the list ... print group,"TTL:",sum(1 for _ in matches)这使您可以根据几个不同的条件进行分组
如果您只想小时而不论日期如何,都可以更改
date_hour
def date_hour(timestamp): return datetime.datetime.fromtimestamp(timestamp).strftime("%H")如果您想按星期几分组,则只需使用
def date_hour(timestamp): return datetime.datetime.fromtimestamp(timestamp).strftime("%w %H")


