How to find difference in years between two dates?
Roy Smith
roy at panix.com
Wed Jul 26 09:35:39 EDT 2006
"thebjorn" <bp.datakortet.no at gmail.com> wrote:
> def age(born):
> now = date.today()
> birthday = date(now.year, born.month, born.day)
> return now.year - born.year - (birthday > now and 1 or 0)
I don't get that last line. There's two things in particular that are
puzzling me.
1) What does "birthday > now" mean? It sounds like you haven't been born
yet.
2) I find the "and 1 or 0" part very confusing. I can't remember all the
minor rules about operator precedence, but I'm sure this works out to some
clever hack involving boolean short-circuit evaluation to get around the
lack of a ternary operator in python. If I need to pull out the reference
manual to decipher what an expression means, it's too complicated. Try
something like:
if birthday > now:
return now.year - born.year - 1
else:
return now.year - born.year
It takes up a little more space, but it's bog easy to understand without
scratching your head or diving into the manual to refresh your memory of
obscure language details.
More information about the Python-list
mailing list