'datetime.date' object has no attribute 'date'

二次信任 提交于 2020-01-01 09:42:15

问题


This code:

import datetime
d_tomorrow = datetime.date.today() + datetime.timedelta(days=1)

class Model(models.Model):
    ...
    timeout = models.DateTimeField(null=True, blank=True, default=d_tomorrow)
    ...

resuls in this error:

'datetime.date' object has no attribute 'date'

What am I doing wrong?


回答1:


d_tomorrow is expected, by the Django ORM, to have a date attribute (apparently), but doesn't.

At any rate, you probably want to use a callable for the default date; otherwise, every model's default date will be "tomorrow" relative to the time the model class was initialized, not the time that the model is created. You might try this:

import datetime

def tomorrow():
  return datetime.date.today() + datetime.timedelta(days=1)

class Model(models.Model):
  timeout = models.DateTimeField(null=True, blank=True, default=tomorrow)



回答2:


I had this problem when using the model from django.contrib.admin. I had two similar models, both with a date field (and both using auto_now_date=True - complete red herring); one worked, one had this error.

Turned out to be

def __unicode__(self):
    return self.date

goes BANG, while this

def __unicode__(self):
    return u'%s' % self.date

works just fine. Which is kind of obvious after the event, as usual.




回答3:


Problem solved:

from datetime import datetime, time, date, timedelta
def tomorrow():
    d = date.today() + timedelta(days=1)
    t = time(0, 0)
    return datetime.combine(d, t)

2015 Update:

Arrow makes this all much more straight forward.

Arrow is a Python library that offers a sensible, human-friendly approach to creating, manipulating, formatting and converting dates, times, and timestamps. It implements and updates the datetime type, plugging gaps in functionality, and provides an intelligent module API that supports many common creation scenarios. Simply put, it helps you work with dates and times with fewer imports and a lot less code.

Arrow is heavily inspired by moment.js and requests.




回答4:


This works for me:

import datetime
from datetime import timedelta

tomorrow = datetime.date.today() + timedelta(days=1)

class Test(models.Model):
    timeout = models.DateTimeField(db_index=True, default=tomorrow)

Alternatively you could use tomorrow = datetime.datetime.now() + timedelta(days=1)




回答5:


I tried out your code and it worked just fine. Can you verify that you are not modifying/redefining the import in some way?

Also try this:

import datetime as DT
d_tomorrow = DT.date.today() + DT.timedelta(days=1)

class Model(models.Model):
    timeout = models.DateTimeField(null=True, blank=True, default=d_tomorrow)


来源:https://stackoverflow.com/questions/3676794/datetime-date-object-has-no-attribute-date

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