python – 描述符’date’需要’datetime.datetime’对象但收到’unicode’

我正在使用活塞为我正在编写的处理重复日历事件的应用程序编写
JSON API.

我的API适用于常规事件,当我尝试添加逻辑来处理重复时,我开始收到以下错误:

descriptor ‘date’ requires a ‘datetime.datetime’ object but received a ‘unicode’

这是我的handlers.py:

from piston.handler import BaseHandler
from lessons.models import NewEvent, EachEvent
import calendar
from datetime import datetime, timedelta

class CalendarHandler(BaseHandler):
allowed_methods = ('GET',)
model = EachEvent
fields = ('actualDate', ('manager', ('firstName', 'lastName')))

def next_date(startDate, recurrence, rangeStart):
    sd = startDate
    while (sd < rangeStart):
        print sd;
        sd += datetime.timedelta(recurrence)
    return sd

def read(self, request, uid, month, year):
    qs = NewEvent.objects.filter(manager__boss = request.user).filter(endDate__gte=datetime.date(year, month, 1)).filter(startDate__lte=datetime.date(year, month, calendar.mdays[month]))
    lessonList = []
    qsList = list(qs)
    for l in qsList:
        if l.frequency == 0:
            x = EachLesson()
            x.lessonID = l.id
            x.actualDate = l.startDate
            x.manager = l.manager
            lessonList.append(x)
        else:
            sd = next_date(l.startDate, l.frequency, datetime.date(year, month, 1))
            while (sd <= datetime.date(year, month, calendar.mdays[month])):
                x = EachLesson()
                x.lessonID = l.id
                x.actualDate = sd
                x.manager = l.manager
                lessonList.append(x)
                sd += datetime.timedelta(recurrence)

    return lessonList

frequency是IntegerField,actualDate,startDate和endDate都是DateField.

我的URLconf接受一个uid,year和month,所有这些都作为参数传递给CalendarHandler.read方法.

最佳答案 通过使用datetime import datetime,timedelta,您已从datetime模块导入datetime类型.因此,当您调用datetime.date时,您正在调用datetime类型的方法.

我想你想要的是使用datetime模块中的日期类型:

>将导入更改为日期时间导入日期时间,timedelta,日期.
>呼叫日期(年,月,1)而不是datetime.date(年,月,1).

点赞