can't compare datetime.datetime to datetime.date

751 views
Skip to first unread message

Rafał Szymański

unread,
Jan 27, 2014, 8:38:20 AM1/27/14
to django...@googlegroups.com
Hi again

I wolud like ask another question.
If someone would be so kind and help that will be great.
I'm in the begining of django tutorial.

I use python3.3 and django1.6

I get error:
can't compare datetime.datetime to datetime.date
Here is my code:
import datetime
from django.utils import timezone
from django.db import models

class Poll(models.Model):
    question = models.CharField(max_length=200)
    pub_date = models.DateField('date published')
    def was_published_recently(self):
        return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
    def __str__(self):
        return self.question

class Choice(models.Model):
    poll = models.ForeignKey(Poll)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)
    def __str__(self):
        return self.choice_text

Thanks in advance
Rafał

i...@simpler.co

unread,
Jan 27, 2014, 9:43:59 AM1/27/14
to django...@googlegroups.com
You're comparing pub_date, which is a datetime.date, to timezone.now(), which is a datetime.datetime. Check the docs at http://docs.python.org/2/library/datetime.html for more.

In order to convert timezone.now() to a date, just call timezone.now().date(), like:

In [1]: from django.utils import timezone

In [3]: timezone.now()

Out[3]: datetime.datetime(2014, 1, 27, 14, 42, 29, 408491, tzinfo=<UTC>)

In [4]: timezone.now().date()

Out[4]: datetime.date(2014, 1, 27)

Rafał Szymański

unread,
Jan 28, 2014, 5:41:28 AM1/28/14
to django...@googlegroups.com
Thank You so much.
Best wishes
Rafal
Reply all
Reply to author
Forward
0 new messages