# Odoo - OpenERP - How to Calculate difference between two dates ? Support
Support
5000
| 2 1 2
0
vote
7928 Views

For years/months/days difference use below codes:

from datetime import datetime, timedelta
from dateutil.relativedelta import relativedelta

date_format = '%Y-%m-%d'

joining_date = '2013-08-23'
current_date = (datetime.today()).strftime(date_format)

d1 = datetime.strptime(joining_date, date_format).date()
d2 = datetime.strptime(current_date, date_format).date()
r = relativedelta(d2,d1)

print r.years
print r.months
print r.days

For minutes difference use below codes:

from datetime import datetime

fmt = '%Y-%m-%d %H:%M:%S'
d1 = datetime.strptime('2010-01-01 17:31:22', fmt)
d2 = datetime.strptime('2010-01-03 17:31:22', fmt)

print (d2-d1).days * 24 * 60

The above doesn't work in cases where the dates don't have the same exact time.

original problem:

from datetime import datetime

fmt = '%Y-%m-%d %H:%M:%S'
d1 = datetime.strptime('2010-01-01 17:31:22', fmt)
d2 = datetime.strptime('2010-01-03 17:31:22', fmt)

daysDiff = (d2-d1).days
print daysDiff
> 2

# convert days to minutes
minutesDiff = daysDiff * 24 * 60

print minutesDiff
> 2880
d2-d1 gives you a datetime.timedelta and when you use days it will only show you the days in the timedelta.

In this case it works fine, but if you would have the following.

from datetime import datetime

fmt = '%Y-%m-%d %H:%M:%S'
d1 = datetime.strptime('2010-01-01 16:31:22', fmt)
d2 = datetime.strptime('2010-01-03 20:15:14', fmt)

daysDiff = (d2-d1).days
print daysDiff
> 2

# convert days to minutes
minutesDiff = daysDiff * 24 * 60

print minutesDiff
> 2880  # that is wrong
It would have still given you the same answer since it still returns 2 for days, it ignores the hour, min and second from the timedelta.

A better approach would be to convert the dates to a common format and then do the calculation.

The easiest way to do this is to convert them to unix timestamps.

Here is the code to do that.

from datetime import datetime
import time

fmt = '%Y-%m-%d %H:%M:%S'
d1 = datetime.strptime('2010-01-01 17:31:22', fmt)
d2 = datetime.strptime('2010-01-03 20:15:14', fmt)

# convert to unix timestamp
d1_ts = time.mktime(d1.timetuple())
d2_ts = time.mktime(d2.timetuple())

# they are now in seconds, subtract and then divide by 60 to get minutes.
print int(d2_ts-d1_ts) / 60
> 3043  # much better Support
Support
5000
| 2 1 2
0
vote

Please try to give a substantial answer. If you wanted to comment on the question or answer, just use the commenting tool. Please remember that you can always revise your answers - no need to answer the same question twice. Also, please don't forget to vote - it really helps to select the best questions and answers!