0

So basically what I want to do is to subtract the date of birth from todays date in order to get a persons age, I've successfully done this, but I can only get it to show the persons age in days.

dateofbirth = 19981128
dateofbirth = list(str(dateofbirth))
now = datetime.date.today()
yr = dateofbirth[:4]
yr = ''.join(map(str, yr))
month = dateofbirth[4:6]
month = ''.join(map(str, month))
day = dateofbirth[6:8]
day = ''.join(map(str, day))
birth = datetime.date(int(yr), int(month), int(day))
age = now - birth
print(age)

In this case, age comes out as days, is there any way to get it as xx years xx months and xx days?

Rafa Viotti
  • 9,998
  • 4
  • 42
  • 62
IsakE
  • 55
  • 5
  • 2
    possible duplicate of [How do I find the time difference between two datetime objects in python?](http://stackoverflow.com/questions/1345827/how-do-i-find-the-time-difference-between-two-datetime-objects-in-python) – AtAFork Nov 07 '14 at 22:38
  • 2
    more likely a duplicate of http://stackoverflow.com/questions/538666/python-format-timedelta-to-string – ComputerDruid Nov 07 '14 at 22:41
  • Aside, you can slice strings directly: `dob = "19981128"; yr = int(dob[:4]); ...` – tom Nov 07 '14 at 22:53

2 Answers2

1

You can use strptime:

>>> import datetime
>>> datetime.datetime.strptime('19981128', '%Y%m%d')
datetime.datetime(1998, 11, 28, 0, 0)
>>> datetime.datetime.now() - datetime.datetime.strptime('19981128', '%Y%m%d')
datetime.timedelta(5823, 81486, 986088)
>>> print (datetime.datetime.now() - datetime.datetime.strptime('19981128', '%Y%m%d'))
5823 days, 22:38:18.039365
Simeon Visser
  • 118,920
  • 18
  • 185
  • 180
1

The result of subtracting two dates in Python is a timedelta object, which just represents a duration. It doesn't "remember" when it starts, and so it can't tell you how many months have elapsed.

Consider that the period from 1st January to 1st March is "two months", and the period from 1st March to 28th April is "1 month and 28 days", but in a non-leap year they're both the same duration, 59 days. Actually, daylight savings, but let's not make this any more complicated than it needs to be to make the point ;-)

There may be a third-party library that helps you, but as far as standard Python libraries are concerned, AFAIK you'll have to roll your sleeves up and do it yourself by finding the differences of the day/month/year components of the two dates in turn. Of course, the month and day differences might be negative numbers so you'll have to deal with those cases. Recall how you were taught to do subtraction in school, and be very careful when carrying numbers from the month column to the days column, to use the correct number of days for the relevant month.

Steve Jessop
  • 273,490
  • 39
  • 460
  • 699