Another interesting way to resolve this issue is by using the library dateutil.
That way we can implement the following code:
from datetime import datetime
from dateutil.relativedelta import relativedelta
a = "2015-08-05 08:12:23"
b = "2015-08-09 08:12:23"
f = "%Y-%m-%d %H:%M:%S"
ini = datetime.strptime(a, f)
fim = datetime.strptime(b, f)
di = abs(relativedelta(ini, fim))
print(f'{di.years} anos, {di.months} meses, {di.days} dias, {di.hours} horas, '
f'{di.minutes} minutos e {di.seconds} segundos.')
Note that the code receives two dates and times in type string, converts them into objects datetime, and then - with the help of the method relativedelta - calculates the difference.
Note also that the result of this method consists of a tuple, with which we can later retrieve each of its elements.
The result of print() is nothing more than the values of each element of the previously generated tuple.
It is working but in other systems it is not? Which systems are these? Explain better, what mistakes are coming up, so it’s hard for anyone to help.
– Paulo