特定日期每小时发生的事件数

时间:2012-12-08 10:53:29

标签: django django-models

我的模型包含“caller_name”和“call_datetime”字段。

我能够在特定月份的每一天获得通话次数:

while start_date <= end_date:
    calls = CDR.objects.filter(start_time__year=str(start_date.year), start_time__month=str(start_date.month), 
                                    start_time__day=str(start_date.day))
    print "Number of calls:", len(calls)
    start_date = start_date + datetime.timedelta(days=1)

类似地,我试图在特定日期每小时获得一些电话。

for i in range(24):
    calls = CDR.objects.filter(start_time__year=str(start_date.year), start_time__month=str(start_date.month),start_time__day=str(start_date.day), start_time__hour=str(i))

发现“start_time__hour”未实现,但以任何方式实现此目的?

2 个答案:

答案 0 :(得分:2)

尝试此解决方法:

day_calls = CDR.objects.filter(start_time__year=str(start_date.year), start_time__month=str(start_date.month),start_time__day=str(start_date.day))

hour_calls = day_calls.extra(select={'hours': 'DATE_FORMAT(start_date, "%%H")'})\
                      .values_list('hours', flat=True)\
                      .distinct()\
                      .order_by('hours')

答案 1 :(得分:1)

您可以使用带有.extra()方法的原始SQL或类似的东西:

for i in range(24):
    dt1 = start_time.replace(hour=i)
    dt2 = dt1 + datetime.timedelta(hours=1)
    calls = CDR.objects.filter(start_time__gte=dt1, start_time__lt=dt2)