9

I want to calculate days difference between current date and previous date. i am trying this code

requiremntObj = CustomerLeads.objects.all()
a = datetime.datetime.now().date()

for i in requiremntObj:
    date1=i.posting_date
    diff = a-date1
    print diff

I got a error unsupported operand type(s) for -: 'datetime.date' and 'unicode'

For current date i am getting datetime object and for date1 i am getting unicode.

posting_date = models.DateField()
vikrant Verma
  • 478
  • 3
  • 8
  • 17
  • is `posting_date` a `CharField` or `DateTimeField`? – Hybrid Dec 19 '16 at 19:52
  • What does the `CustomerLeads` model look like? Is `posting_date` a proper [DateTimeField](https://docs.djangoproject.com/en/1.10/ref/models/fields/#datetimefield)? If not: Fix your model! – dhke Dec 19 '16 at 19:53

2 Answers2

15

If you have DateTimeField you can use:

delta = datetime.now().date() - posting_date
print delta.days

If it is string, then you have to convert:

from datetime import datetime
date_format = "%m/%d/%Y"
a = datetime.strptime(str(datetime.now().date()), date_format)
b = datetime.strptime(str(posting_date), date_format)
delta = b - a
print delta.days

Here is post.

Community
  • 1
  • 1
Zagorodniy Olexiy
  • 2,132
  • 3
  • 22
  • 47
3

This code for HTML in Django

<p> {{ to_date|timeuntil:from_date }} </p>

This code for server site in python

import datetime

from_date = datetime.datetime(2019, 10, 21)

to_date   = datetime.datetime(2019, 10, 25)

result = to_date - from_date
print(result.days)
FZs
  • 16,581
  • 13
  • 41
  • 50
jahurul25
  • 159
  • 4