Andrew
Andrew

Reputation: 3999

Subtract dates in Django?

I have two DateField variables and I would like to subtract them and return the difference as a number of months to the nearest month. How might I do this?

Thanks for the help!

Upvotes: 1

Views: 3171

Answers (3)

adnan dogar
adnan dogar

Reputation: 211

def date_diff:
now = datetime.now().date()
s=seo_job.job_end_date.replace(hour=23,minute=59,second=59).date()
#seo_job.job_end_date an end date that is saved in db
return (now-s)

Upvotes: 0

ezod
ezod

Reputation: 7411

For a definite answer using calendar month lengths:

months = lambda a, b: abs((a.year - b.year) * 12 + a.month - b.month)

Example:

>>> import datetime
>>> a = datetime.date(2011, 2, 8)
>>> b = datetime.date(2010, 5, 14)
>>> months(a, b)
9

Edit, if you want to round based on days too:

months = lambda a, b: abs((a.year - b.year) * 12 + a.month - b.month) + int(abs(a.day - b.day) > 15)

Example:

>>> import datetime
>>> a = datetime.date(2011, 2, 8)
>>> b = datetime.date(2010, 5, 14)
>>> months(a, b)
9
>>> b = datetime.date(2010, 5, 30)
>>> months(a, b)
10

Upvotes: 3

joshcartme
joshcartme

Reputation: 2747

Datefields are datetime.date instances. You can directly subtract them which will give you a timedelta. You can access the number of days a timedelta represents via timedelta.days. Lets say the datefield self.date is set to two months ago:

today = datetime.date.today()
n = today - self.date
months = int(n.days/30)

should give you the number of months in this case 2. Depending on how you define the nearest month you may need to round rather than casting to an int.

Upvotes: 6

Related Questions