34

I have the following python code:

from django.db import models
from datetime import datetime

class Poll(models.Model):
    question = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')
    def __unicode__(self):
        return self.question
    def was_published_today(self):
        return self.pub_date.date() == datetime.date.today()

In a python shell, I am trying to run:

p = Poll.objects.get(pk=1)
p.was_published_today()

The first line works fine but the second line gives me this error:

AttributeError: 'method_descriptor' object has no attribute 'today'

3 Answers 3

63

You probably want "import datetime", not "from datetime import datetime".

"date" is a class on the datetime module, but it is also a method on the "datetime.datetime" class.

1
  • 7
    or from datetime import datetime, date
    – Josh
    Feb 18, 2019 at 13:04
33

The top answer is correct, but if you don't want to import all of datetime you can write

from datetime import date

and then replace

datetime.date.today()

with

date.today()
2
  • In my scenario, this solution helped me. Thanks Jan 30, 2018 at 12:53
  • 1
    datetime.date.today() didn't work, but date.today() worked. Feb 2, 2022 at 4:00
5

You need do like this one (ipython output)

In [9]: datetime.today().date()
Out[9]: datetime.date(2011, 2, 5)

So need to be

def was_published_today(self):
        return self.pub_date.date() == datetime.today().date()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.