Python calculating time difference, to give ‘years, months, days, hours, minutes and seconds’ in 1

Use a relativedelta from the dateutil package. This will take into account leap years and other quirks.

import datetime
from dateutil.relativedelta import relativedelta

a = '2014-05-06 12:00:56'
b = '2013-03-06 16:08:22'

start = datetime.datetime.strptime(a, '%Y-%m-%d %H:%M:%S')
ends = datetime.datetime.strptime(b, '%Y-%m-%d %H:%M:%S')

diff = relativedelta(start, ends)

>>> print "The difference is %d year %d month %d days %d hours %d minutes" % (diff.years, diff.months, diff.days, diff.hours, diff.minutes)
The difference is 1 year 1 month 29 days 19 hours 52 minutes

You might want to add some logic to print for e.g. "2 years" instead of "2 year".


diff is a timedelta instance.

for python2, see: https://docs.python.org/2/library/datetime.html#timedelta-objects

for python 3, see: https://docs.python.org/3/library/datetime.html#timedelta-objects

from docs:

timdelta instance attributes (read-only):

  • days
  • seconds
  • microseconds

timdelta instance methods:

  • total_seconds()

timdelta class attributes are:

  • min
  • max
  • resolution

You can use the days and seconds instance attributes to calculate what you need.

for example:

import datetime

a = '2014-05-06 12:00:56'
b = '2013-03-06 16:08:22'

start = datetime.datetime.strptime(a, '%Y-%m-%d %H:%M:%S')
ends = datetime.datetime.strptime(b, '%Y-%m-%d %H:%M:%S')

diff = start - ends

hours = int(diff.seconds // (60 * 60))
mins = int((diff.seconds // 60) % 60)