【问题标题】:Strftime error PythonStrftime错误Python
【发布时间】:2018-11-28 11:11:57
【问题描述】:

我正在调用一个函数来计算司机收入,但我不断收到此错误:

"line 396, in driver_get_revenue
    monthly[month.strftime("%m")] = orders.count() * settings.DRIVER_DELIVERY_PRICE
AttributeError: 'int' object has no attribute 'strftime'"

函数是这样的:

def driver_get_revenue(request):

        driver = JWTAuthentication().authenticate(request)[0].driver


        #Returns the difference between date and time.
        from datetime import timedelta

        revenue = {}
        monthly = {}
        yearly = {}


        today = timezone.now()
        month = today.month
        year = today.year


        #Created a range to calculate the current weekday.
        current_weekdays = [today + timedelta(days = i) for i in range(0 - today.weekday(), 7 - today.weekday())]

        for day in current_weekdays:
            orders = Order.objects.filter(
                driver = driver,
                status = Order.DELIVERED,
                created_at__year = day.year,
                created_at__month = day.month,
                created_at__day = day.day
            )
            revenue[day.strftime("%A")] = orders.count() * settings.DRIVER_DELIVERY_PRICE




        for day in range(0, 30):
            orders = Order.objects.filter(
                    driver = driver,
                    status = Order.DELIVERED,
                    created_at__month = month,
                    created_at__day = day
                )

          (Line 396)  monthly[month.strftime("%m")] = orders.count() * settings.DRIVER_DELIVERY_PRICE




        for month in range(0, 12):
            orders = Order.objects.filter(
                    driver = driver,
                    status = Order.DELIVERED,
                    created_at__year = year,
                    created_at__month = month

                )

        yearly[year.strftime("%y")] = orders.count() * settings.DRIVER_DELIVERY_PRICE

        return JsonResponse({"revenue": revenue,
                            "month": monthly,
                            "yearly": yearly})

我不确定我哪里出错了。我标记了第 396 行,以便您看到错误在哪里。任何帮助将不胜感激。

谢谢。

【问题讨论】:

  • 这里根本不需要strftimemonth 已经是整数月份了。

标签: python django strftime


【解决方案1】:

当你这样做时:month = today.month,月份变成一个整数。 strftime 函数适用于日期时间对象,而不适用于整数。

因此,month.strftime("%m") 不起作用。

改用day.strftime("%m"),或者只是month,这取决于您的要求。

如果您正在寻找月份的名称,您可以这样做:

today = timezone.now()
month = today.month
month_name = today.strftime("%B") # e.g. December
...

...并在您的代码中使用month_name 变量。

【讨论】:

  • 我正在寻找返回的月份名称。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-11-09
  • 2019-01-02
  • 2015-04-14
  • 2015-04-30
  • 1970-01-01
  • 2013-07-10
  • 1970-01-01
相关资源
最近更新 更多