Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

I want to know how many years, months, days, hours, minutes and seconds in between '2014-05-06 12:00:56' and '2012-03-06 16:08:22'. The result shall looked like: “the difference is xxx year xxx month xxx days xxx hours xxx minutes”

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

if I do:

diff.days

It gives the difference in days.

What else I can do? And how can I achieve the wanted result?

like image 731
Mark K Avatar asked Aug 22 '14 03:08

Mark K


2 Answers

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".

like image 155
mhawke Avatar answered Oct 12 '22 17:10

mhawke


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)
like image 41
Corey Goldberg Avatar answered Oct 12 '22 18:10

Corey Goldberg