Know years, months, days, hours, etc ... That have passed since a certain date

0

I would like to know how I make the output of the difference between two dates stay the way I want, in this case I would like it to be:

  

Since 16 - 07 - 2014 23:00:00 have passed: X years, Y months, K days, Z hours, W minutes, S secs

What I have:

import datetime
d1 = datetime.datetime(2014,7,16,23)
d2 = datetime.datetime.now()

diff = d2 - d1

print(diff) # este não é o output que quero.
    
asked by anonymous 28.07.2017 / 15:54

1 answer

1

In a very simplified way you can do:

import datetime

d1 = datetime.datetime(2014,7,16,23)
d2 = datetime.datetime.now()

diff = d2 - d1

days = diff.days
years, days = days // 365, days % 365
months, days = days // 30, days % 30

seconds = diff.seconds
hours, seconds = seconds // 3600, seconds % 3600
minutes, seconds = seconds // 60, seconds % 60

print("Desde {} passaram {} anos, {} meses, {} dias, {} horas, {} minutos e {} segundos".format(d1, years, months, days, hours, minutes, seconds))

In the object diff we will have the difference between the dates. By the attribute day and seconds we take this difference in relation to the number of days and seconds, respectively. To know the number of years, we calculate the entire division between the number of days by 365 and update the value of days to discount the amount relative to those years. With the month, we calculated the division by 30 and updated the number of days again.

For the hours and minutes the logic is exactly the same, dividing the number of seconds by 3600 and 60, respectively.

It is worth remembering that this difference is approximate, as it does not take leap year considerations within the range considered, nor the exact number of days in each month.

  

See working at Ideone .

    
03.08.2017 / 16:16