开发者

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

开发者 https://www.devze.com 2023-01-15 17:22 出处:网络
This code: import datetime d_tomorrow = datetime.date.today() + datetime.timedelta(days=1) class Model(models.Model):

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?


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)


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)

models.DateTimeField expects the value to be datetime.datetime, not datetime.date

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.


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.


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)


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)
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号