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?
datetime' has no attribute 'datetime'. To resolve the problem, we just have to “import datetime” instead of “from datetime import datetime” as we did it above. Looks good.
The error "AttributeError module 'datetime' has no attribute 'utcnow'" occurs when we try to call the utcnow method directly on the datetime module. To solve the error, use the following import import datetime and call the utcnow method as datetime. datetime. utcnow() .
today() The today() method of date class under DateTime module returns a date object which contains the value of Today's date. Returns: Return the current local date.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With