描述符' date'需要一个&datetime.datetime'对象但收到了' int',但它是约会?

时间:2017-06-09 09:01:04

标签: python date datetime

我试图在我的python代码中获取当前年份。由于某种原因,我收到以下错误

  

描述符' date'需要一个&datetime.datetime'对象但收到了   ' INT'

但是,如果我打印数据类型,它说它是一个日期....

from datetime import timedelta, datetime, date

def month_list(request):
    today = datetime.now()
    print today
    print type(today)
    year = today.year
    month_list = []
    for i in range(1, 13):
        month_list.append((i, datetime.date(year, i, 1).strftime('%B')))
    print month_list
    return render(request, "app/template.html")

在控制台中

2017-06-09 08:53:18.852041
<type 'datetime.datetime'>
Internal Server Error: /app/month_list/
Traceback (most recent call last):
  File "/Library/Python/2.7/site-packages/django/core/handlers/base.py", line 149, in get_response
    response = self.process_exception_by_middleware(e, request)
  File "/Library/Python/2.7/site-packages/django/core/handlers/base.py", line 147, in get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/Library/Python/2.7/site-packages/django/contrib/auth/decorators.py", line 23, in _wrapped_view
    return view_func(request, *args, **kwargs)
  File "/Users/username/Documents/Database/project/app/views.py", line 468, in month_list
    month_list.append((i, datetime.date(year, i, 1).strftime('%B')))
TypeError: descriptor 'date' requires a 'datetime.datetime' object but received a 'int'

我在另一个视图中使用了相同的代码行,并且工作正常...猜猜我在这里做了些蠢事......?

由于

1 个答案:

答案 0 :(得分:2)

我认为它应该是month_list.append((i, date(year, i, 1).strftime('%B')))

由于您已经从datetime模块导入了日期,因此您可以直接引用它。