How to find difference in years between two dates?

Gerhard Fiedler gelists at gmail.com
Wed Jul 26 18:49:03 EDT 2006


On 2006-07-26 17:50:43, thebjorn wrote:

> I don't agree that the irregular sized months cause a problem in this
> case. They do cause a problem if you're asking "when is today + one
> month?", i.e. there isn't an unambiguous answer to that question in
> general (e.g. if today was January 31). We're asking a different kind
> of question though: "has it been at least one month since January 31?",
> the answer would be no on Feb 29 and yes on Mar 1.

It's still ambiguous. That's why pretty much no library offers months as
units of date differences. They offer days (like DateTimeDelta in
mxDateTime does). 

For example, the mxDateTime guys say about their RelativeDateTime (which
allows months as differences): 
"""
Note that dates like Date(1999,1,30) + RelativeDateTime(months=+1) are not
supported. The package currently interprets these constructions as
Date(1999,2,1) + 30, thus giving the 1999-03-02 which may not be what you'd
expect.
"""

I think your original approach (difference of years, adjusted for whether
the date of the birthday has already passed in the current year or not) is
the unambiguous way to get the age. Other methods based on date differences
in days need careful adjustments for odd cases involving leap years.

Gerhard




More information about the Python-list mailing list