[Answer]-Django DateField subtraction

2👍

You’re doing something very odd. You have django model code, which defines Field objects which contain no value. Only instances contain field values (you’re defining things on the class level) so whatever you’re doing should be put in a class method.

Perhaps you’re confused because django’s metaclass magic converts references to those attributes to python values from the database?

class MyModel(models.Model):
    foo = models.DateField()

    print foo  # is a models.DateField

    def get_foo_after_django_magic(self):
        print self.foo  # is a datetime() instance

0👍

DateFields are not the same as python datetime instances so you cannot do what you are trying to do because DateFields do not allow that operation. The answer Raunak provided is correct.

If you had a model that had DateField as an attribute in it you would then be to do something like.

my_object = MyModelWithDateField.object.get(pk=1)
diff = datetime.today - my_object.some_datefield
👤esse

-1👍

You can subtract the values for the Datefiedl i.e.

df = datetime.date(year=2005, month=11, day=1)
di = datetime.date(year=2005, month=11, day=6)

You can not directly perform the action on the datefield’s

When you try to subtract two date object the diff’s returns a timedelta instanace

>>> df = datetime.date(year=2005, month=11, day=1)
>>> di = datetime.date(year=2005, month=11, day=6)
>>> di -d5
datetime.timedelta(5)

Leave a comment