3

I have 2 person's birth information, I want to do some analysis on them. Like, the difference between their age, seconds, years+months+days. I tried this:

from datetime import date
a = date(1991, 07, 20)
b = date(1999, 06, 06)
print((a-b).days)
-2878

this gives me 2878 days, but i want to calculate years + months + days i tried to divide 2878/365, but i want the exact calculations How can i approach this?

Expected Output:

7 years x months x days
Tarun K
  • 469
  • 9
  • 20
  • Please this SO post, that should get your started: https://stackoverflow.com/a/151211/2186184 – Jonathan Jun 12 '18 at 08:38
  • @kabanus sorry typos – Tarun K Jun 12 '18 at 08:41
  • There are no exact calculations, because "month" and "year" are inexact measures. Is 366 days a year, or a year and a day? Is 28 days a month, or three days short of that? If imprecise is good enough, just divide by what you think "month" and "year" should be, as you did. If you want "exact calculations", stick with days. – Amadan Jun 12 '18 at 08:45
  • Just like we say when someone ask our birthday, like person a is `26 years 10 months 23 days` – Tarun K Jun 12 '18 at 08:47
  • @Darkstarone thanks I got this – Tarun K Jun 12 '18 at 08:48

2 Answers2

11

Use datetime and dateutil:

from datetime import datetime
from dateutil import relativedelta

date1 = datetime(1991, 7, 20)
date2 = datetime(1999, 6, 6)

diff = relativedelta.relativedelta(date2, date1)

years = diff.years
months = diff.months
days = diff.days

print('{} years {} months {} days'.format(years, months, days))
# 7 years 10 months 17 days
Austin
  • 25,759
  • 4
  • 25
  • 48
2

For strict differences, i.e. differences between years, months and days, you can use the attributes of timedelta objects.

from datetime import date

a = date(1991, 7, 20)
b = date(1999, 6, 6)

months = a.month - b.month
years = a.year - b.year
days = a.day - b.day

print('{0} years, {1} months, {2} days'.format(years, months, days))

-8 years, 1 months, 14 days

For time-aware differences, you can use 3rd party dateutil as per @Austin's solution.

jpp
  • 159,742
  • 34
  • 281
  • 339