Bruno Desthuilliers wrote: > thebjorn wrote: > > For the purpose of finding someone's age I was looking for a way to > > find how the difference in years between two dates, so I could do > > something like: > > > > age = (date.today() - born).year > > > > but that didn't work (the timedelta class doesn't have a year > > accessor). > > > > I looked in the docs and the cookbook, but I couldn't find anything, so > > I came up with: > > > > 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.e. calculate the "raw" years first and subtract one if he hasn't had > > his birthday yet this year... It works, but I'd rather use a standard > > and generic approach if it exists...? > > You may want to have a look at mxDatetime, which has a RelativeDateTime > type that seems to do what you want: > http://www.egenix.com/files/python/mxDateTime.html >
Which pieces of the following seem to be working to you? >>> import mx.DateTime >>> f = mx.DateTime.RelativeDateTimeDiff >>> d = mx.DateTime.Date >>> f(d(2000, 2, 29), d(2001, 2, 28)) <RelativeDateTime instance for 'YYYY-(-11)-(-28) HH:MM:SS' at 0xaee170> >>> f(d(2000, 2, 29), d(2001, 3, 1)) <RelativeDateTime instance for '(-0001)-MM-(-01) HH:MM:SS' at 0xb06530> >>> f(d(2001, 1, 31), d(2001, 2, 28)) <RelativeDateTime instance for 'YYYY-MM-(-28) HH:MM:SS' at 0xaee170> >>> g = lambda x, y: f(y, x) >>> g(d(2000, 2, 29), d(2001, 2, 28)) <RelativeDateTime instance for 'YYYY-(+11)-(+30) HH:MM:SS' at 0xb06580> >>> g(d(2000, 2, 29), d(2001, 3, 1)) <RelativeDateTime instance for '(+0001)-MM-DD HH:MM:SS' at 0xaee170> >>> g(d(2001, 1, 31), d(2001, 2, 28)) <RelativeDateTime instance for 'YYYY-MM-(+28) HH:MM:SS' at 0xb06580> >>> and going the other way, adding one month to 31 January gives you some date in March which is ludicrous. -- http://mail.python.org/mailman/listinfo/python-list