【问题标题】:OverflowError mktime argument out of rangeOverflowError mktime 参数超出范围
【发布时间】:2015-12-14 17:19:06
【问题描述】:

在解决了一个幼稚的日期时间问题后,我面临着一个关于生成图表的新问题。现在我得到 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()))

【问题讨论】:

  • 导致错误的dt.timetuple() 的值是多少?
  • 在 3001 的某个地方。我不明白为什么这个函数会不停地运行。
  • 所以问题不在于 mktime,而是在您期望的时候没有结束的循环。当你在每个循环中打印lastmonthlastyear 时,你得到了什么值?你期待什么?设置 lastmonth = 0 在我看来是个错误。
  • 问题一定在while loop里面。问题仅在月份 = 12 时存在,这就是它一直工作到 01/12 的原因。无论如何,我不知道如何解决它。主要思想是制作从去年当月到今年当月的堆积面积图。循环不会停止,然后它会在数年和数月内迭代。不知道为什么。我确信答案是直截了当的,但我无法解决它

标签: python django mktime


【解决方案1】:

我认为问题在于这种情况。

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

在 12 月期间,month=12,因此 lastmonth &lt;= int(month) 将始终为 True。所以循环总是返回 True,即使一次 lastyear 比当前的 year 更多。

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

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

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

【讨论】:

  • 你是个天才。它解决了我的问题。现在,请你解释一下为什么它确实像我一样愚蠢吗?
  • 其实我觉得我之前写的答案是错误的,只能在12月份有效。请参阅我的更新答案。理解代码的最佳方法是添加大量打印语句,并检查它是否按您期望的方式工作。
  • 您的最后一个答案仍然有效,所以我将使用那个答案。无论如何,我需要理解这个逻辑,因为在这种情况下,我会很困惑。
猜你喜欢
  • 1970-01-01
  • 2014-01-25
  • 2019-05-04
  • 2022-01-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多