def changeTime(allTime): '''时间转换的一个函数''' day = 24 * 60 * 60 hour = 60 * 60 min = 60 if allTime < 60: return "%d sec" % math.ceil(allTime) elif allTime > day: days = divmod(allTime, day) return "%d days, %s" % (int(days[0]), changeTime(days[1])) elif allTime > hour: hours = divmod(allTime, hour) return '%d hours, %s' % (int(hours[0]), changeTime(hours[1])) else: mins = divmod(allTime, min) return "%d mins, %d sec" % (int(mins[0]), math.ceil(mins[1])) @csrf_exempt def questionnaire_statistic(request): ''' 计算: 1、问卷访问量:查看questionnaireitem 2、问卷回收量:提交问卷的数量 3、问卷回收率:(回收量/访问量)* 100% ### "%s%%" % (recycled / pv * 100) 4、问卷平均完成时间:提交问卷花费的时间和/回收量 5、每两个小时的提交问卷的数量 ''' res = defaultdict(dict) pv = QuestionnaireItem.objects.filter(questionnaire_id=request.GET.get("questionnaire_id")).count() recycled = QuestionnaireItem.objects.filter(questionnaire_id=request.GET.get("questionnaire_id"), status="submitted").count() if pv>0: rate = "%s%%" % (recycled / pv * 100) res["rate"] = rate elapsed_time = QuestionnaireItem.objects.filter(questionnaire_id=request.GET.get("questionnaire_id"), status="submitted").aggregate(sum_elapsed_time = Sum("elapsed_time")) if recycled>0 : avg_time = elapsed_time["sum_elapsed_time"]/recycled #转换avg_time avg_time = changeTime(avg_time) res["avg_time"] = avg_time #####time#### utimes = QuestionnaireItem.objects.filter(status='submitted').values('submit_time') uts = [] for i in utimes: a = i["submit_time"].strftime("%Y-%m-%d %H:%M:%S") timeArray = time.strptime(a, "%Y-%m-%d %H:%M:%S") timeStamp = int(time.mktime(timeArray)) uts.append(timeStamp) #0 调查问卷开始的时间,结束的时间,每两个小时统计一下数量 start_datetime = Questionnaire.objects.filter(id=request.GET.get("questionnaire_id")).values("start_datetime").first() end_datetime = Questionnaire.objects.filter(id=request.GET.get("questionnaire_id")).values("end_datetime").first() #转化为时间戳 b = start_datetime["start_datetime"].strftime("%Y-%m-%d %H:%M:%S") timeArray1 = time.strptime(b, "%Y-%m-%d %H:%M:%S") start_time = int(time.mktime(timeArray1)) print start_time c = end_datetime["end_datetime"].strftime("%Y-%m-%d %H:%M:%S") timeArray2 = time.strptime(c, "%Y-%m-%d %H:%M:%S") end_time = int(time.mktime(timeArray2)) print end_time time_whole = [] for x in range(start_time, end_time,7200): time_whole.append(x) print time_whole tmp = [] for ut in uts: for t in time_whole[::-1]: # 倒叙 if ut >= t: tmp.append(t) break # print tmp tmp2 = dict.fromkeys(range(start_time, end_time, 7200), 0) # print tmp2 for x in tmp: tmp2[x] += 1 count_whole = [tmp2[x] for x in time_whole] print count_whole res["pv"] = pv res["recycled"] = recycled res["time_whole"] = time_whole res["count_whole"] = count_whole return JsonResponse(res)