calculate an age using two dates

Asked by JamesPanteleone

I have no clue how to do calculate an age using two dates. Any help is really welcome.

Question information

Language:
English Edit question
Status:
Solved
For:
SikuliX Edit question
Assignee:
No assignee Edit question
Solved by:
vitalliuss
Solved:
Last query:
Last reply:
Revision history for this message
Best vitalliuss (vitalliuss) said :
#1

Try this:

from datetime import *
d = date(1990, 5, 29)
now = date.today()
timedelta = now-d
years = str(timedelta/365).split(' ')
print years[0]

Also this page can be helpful: http://docs.python.org/library/datetime.html

Revision history for this message
RaiMan (raimund-hocke) said :
#2

@vitalliuss
principally ok, but the semantics are not ok:
years = str(timedelta/365).split(' ')

timedelta/365 works, but the result are still days - you take it as years and the excerpt of the year is too complicated

better and more straightforward
years = timedelta.days/365

Revision history for this message
vitalliuss (vitalliuss) said :
#3

@RaiMan

Well done, this solution seems to be best.

Unfortunately ideal solution requires leap years support.
For example if "now" will be set to 23th of May 2012 delta days become equal 8030. 8030/365=22. 6 leap years was uncounted.
Do you have any ideas about it?

Revision history for this message
RaiMan (raimund-hocke) said :
#4

@ vitalliuss

The above solution is only usable if you accept the leap years problem, when dividing by 365.
The time delta counts days, which do not have a leap year problem.

BTW: timedelta.days/365 gives 22 and not 22.6 (integer division)

So for this purpose the leap years do no harm.

But if you really want to minimize the "error":
correctLeap = 365*4+1
theDays = timedelta.days
years = (theDays - theDays/correctLeap)/365

this corrects the days value by subtracting the contained leap days before dividing by 365 (error +/-1)

But this does not take into account, that years ending with 00 are normal years ;-)

Revision history for this message
JamesPanteleone (jamesp) said :
#5

Thanks vitalliuss, that solved my question.