OverflowError mktime 参数超出范围

OverflowError mktime argument out of range

在解决了一个天真的日期时间问题后,我在生成图表的视图上遇到了一个新问题。现在我得到 mktime 参数超出范围 。 我不知道如何解决它。我没有编写代码,我正在使用我同事的代码,但我似乎无法理解它为什么会失败。我认为这与一个运行超时并弹出错误的函数有关。

@login_required(login_url='/accounts/login/')
def loggedin(request):
    data = []
    data2 = []
    data3 = []
    dicdata2 = {}
    dicdata3 = {}
    datainterior = []
    today = timezone.localtime(timezone.now()+timedelta(hours=1)).date()
    tomorrow = today + timedelta(1)
    semana= today - timedelta(7)
    today = today - timedelta(1)
    semana_start = datetime.combine(today, time())
    semana_start = timezone.make_aware(semana_start, timezone.utc)
    today_start = datetime.combine(today, time())
    today_start = timezone.make_aware(today_start, timezone.utc)
    today_end = datetime.combine(tomorrow, time())
    today_end = timezone.make_aware(today_end, timezone.utc)
    for modulo in Repository.objects.values("des_especialidade").distinct():
        dic = {}
        mod = str(modulo['des_especialidade'])
        dic["label"] = str(mod)
        dic["value"] = Repository.objects.filter(des_especialidade__iexact=mod).count()
        data.append(dic)
    for modulo in Repository.objects.values("modulo").distinct():
        dic = {}
        mod = str(modulo['modulo'])
        dic["label"] = str(mod)
        dic["value"] = Repository.objects.filter(modulo__iexact=mod, dt_diag__gte=semana_start).count()
        datainterior.append(dic)
        # print mod, Repository.objects.filter(modulo__iexact=mod).count()
        # data[mod] = Repository.objects.filter(modulo__iexact=mod).count()
    dicdata2['values'] = datainterior
    dicdata2['key'] = "Cumulative Return"
    dicdata3['values'] = data
    dicdata3['color'] = "#d67777"
    dicdata3['key'] = "Diagnosticos Identificados"
    data3.append(dicdata3)
    data2.append(dicdata2)



    #-------sunburst
    databurst = []
    dictburst = {}
    dictburst['name'] = "CHP"
    childrenmodulo = []
    for modulo in Repository.objects.values("modulo").distinct():
        childrenmodulodic = {}
        mod = str(modulo['modulo'])
        childrenmodulodic['name'] = mod
        childrenesp = []
        for especialidade in Repository.objects.filter(modulo__iexact=mod).values("des_especialidade").distinct():
            childrenespdic = {}
            esp = str(especialidade['des_especialidade'])
            childrenespdic['name'] = esp
            childrencode = []
            for code in Repository.objects.filter(modulo__iexact=mod,des_especialidade__iexact=esp).values("cod_diagnosis").distinct():
                childrencodedic = {}
                codee= str(code['cod_diagnosis'])
                childrencodedic['name'] = 'ICD9 - '+codee
                childrencodedic['size'] = Repository.objects.filter(modulo__iexact=mod,des_especialidade__iexact=esp,cod_diagnosis__iexact=codee).count()
                childrencode.append(childrencodedic)
            childrenespdic['children'] = childrencode



            #childrenespdic['size'] = Repository.objects.filter(des_especialidade__iexact=esp).count()
            childrenesp.append(childrenespdic)
        childrenmodulodic['children'] = childrenesp
        childrenmodulo.append(childrenmodulodic)
    dictburst['children'] = childrenmodulo
    databurst.append(dictburst)
    # print databurst



    # --------stacked area chart
    datastack = []
    for modulo in Repository.objects.values("modulo").distinct():
        datastackdic = {}
        mod = str(modulo['modulo'])
        datastackdic['key'] = mod
        monthsarray = []
        year = timezone.localtime(timezone.now()+timedelta(hours=1)).year
        month = timezone.localtime(timezone.now()+timedelta(hours=1)).month
        last = timezone.localtime(timezone.now()+timedelta(hours=1)) - relativedelta(years=1)
        lastyear = int(last.year)
        lastmonth = int(last.month)
        #i = 1
        while lastmonth <= int(month) or lastyear<int(year):
            date = str(lastmonth) + '/' + str(lastyear)
            if (lastmonth < 12):
                datef = str(lastmonth + 1) + '/' + str(lastyear)
            else:
                lastmonth = 01
                lastyear = int(lastyear)+1
                datef = str(lastmonth)+'/'+ str(lastyear)
                lastmonth = 0
            datainicial = datetime.strptime(date, '%m/%Y')
            datainicial = timezone.make_aware(datainicial, timezone.utc)
            datafinal = datetime.strptime(datef, '%m/%Y')
            datafinal = timezone.make_aware(datafinal, timezone.utc)
            #print "lastmonth",lastmonth,"lastyear", lastyear
            #print "datainicial:",datainicial,"datafinal: ",datafinal
            filtro = Repository.objects.filter(modulo__iexact=mod)
            count = filtro.filter(dt_diag__gte=datainicial, dt_diag__lt=datafinal).count()
            conv = datetime.strptime(date, '%m/%Y')
            ms = datetime_to_ms_str(conv)
            monthsarray.append([ms, count])
            #i += 1
            lastmonth += 1
        datastackdic['values'] = monthsarray
        datastack.append(datastackdic)
        #print datastack


    if request.user.last_login is not None:
        #print(request.user.last_login)
        contador_novas = Repository.objects.filter(dt_diag__lte=today_end, dt_diag__gte=today_start).count()
    return render_to_response('loggedin.html',
                              {'user': request.user.username, 'contador': contador_novas, 'data': data, 'data2': data2,
                               'data3': data3,
                               'databurst': databurst, 'datastack':datastack})


def datetime_to_ms_str(dt):
    return str(1000 * mktime(dt.timetuple()))

我认为问题出在这种情况下。

while lastmonth <= int(month) or lastyear<int(year):

12 月期间,month=12,因此 lastmonth <= int(month) 将始终是 True。所以循环总是 return 为真,即使有一次 lastyear 比当前的 year 多。

如果循环是在前一年,或者循环是在当年但月份不是未来,你要循环。因此,我认为您想将其更改为以下内容:

while lastyear < year or (lastyear == year and lastmonth <= month):

为了确保代码正常工作并理解它,您需要在循环中添加大量打印语句,查看 lastmonthlastyear 是如何变化的,并检查循环在您期望的时候退出。您还需要针对 yearmonth 的其他值对其进行测试,以便它不会在下个月中断。理想情况下,您希望将这段代码提取到一个单独的函数中。如果只 returned 一个 (month, year) 整数列表,而不是同时进行大量日期格式化,那么它会更容易理解循环。那么添加单元测试就更容易了。