Descriptor 'date' requires a 'datetime.datetime' object but received a 'unicode'

可紊 提交于 2019-12-07 16:21:17

问题


I am using piston to write a JSON api for an application I am writing which handles recurring calendar events.

My API was working for regular events, when I attempted to add logic to handle the recurrence, I started getting the following error:

descriptor 'date' requires a 'datetime.datetime' object but received a 'unicode'

Here is my 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 is an IntegerField, actualDate, startDate, and endDate are all DateField.

My URLconf accepts a uid, year, and month, all of which are passed as parameters to the CalendarHandler.read method.


回答1:


By using from datetime import datetime, timedelta you have imported the datetime type from the datetime module. Thus when you call datetime.date you are calling a method on the datetime type.

I think what you want is to use the date type from the datetime module:

  1. Change your import to from datetime import datetime, timedelta, date.
  2. Call date(year, month, 1) instead of datetime.date(year, month, 1).


来源:https://stackoverflow.com/questions/10865143/descriptor-date-requires-a-datetime-datetime-object-but-received-a-unicode

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!