How to find difference in years between two dates?
thebjorn
BjornSteinarFjeldPettersen at gmail.com
Wed Jul 26 16:50:43 EDT 2006
John Machin wrote:
> thebjorn wrote:
[...]
> >
> > def age(born):
> > now = date.today()
> > birthday = date(now.year, born.month, born.day)
>
> Bad luck if the punter was born on 29 Feb and the current year is not a
> leap year.
Good catch! Thanks!
[..]
> Holy code bloat, Batman! Try this:
>
> return now.year - born.year - (birthday > now)
yuck :-)
[...]
> It's the irregular-size months that cause the problems. If you can work
> out the months difference, then just floor_div by 12 to get the years
> difference.
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.
> Below is some code from the ancient times when everybody and his dog
> each had their own date class :-)
[...]
Wow. I'm speechless. (any reason you didn't want to use the calendar
module?)
-- bjorn
More information about the Python-list
mailing list