How to find difference in years between two dates?

thebjorn bp.datakortet.no at gmail.com
Thu Jul 27 13:01:46 EDT 2006


John Machin wrote:
> thebjorn wrote:
[...]
> > You give a good argument that the concept of a month is fuzzy
>
> Sorry,  I can't imagine where you got "fuzzy" from. Perhaps you mean
> some other word. The concept is capable of being expressed precisely.

and the second to last date in January plus a month is..?

> > > Sorry, I don't understand. Why are you speechless? What would I want to
> > > use the calendar module for? Apart from the leap() function and the
> > > table of days in a month, the calendar module doesn't have any of the
> > > functionality that one would expect in a general-purpose date class.
> >
> > Well, I thought replacing a 4 line function with 31 lines, 13 of which
> > duplicated functionality in the standard library was overkill.
>
> I think you missed the point that the lines I quoted were straight out
> of a self-contained library that existed (in C as well as Python) way
> before the datetime module was a gleam in Fred & the timbot's eyes.

I'm guessing you missed that I was looking for a method in the stdlib
to do this, and failing that an idiomatic solution...

> Even if I had noticed a leap year function in the calendar module, I
> would probably not have used it. The Python version of the module was
> just a stopgap while I fiddled with getting a C extension going. The C
> leap year function doesn't have any of that modulo stuff in it.

I'm sure it doesn't. You might want to look at the assembly your C
compiler produces for a modulo-power-of-2 operation...

> > I came up with this yesterday which seems sufficient?
> >
> >     def yeardiff(a, b):
> >       y = a.year - b.year
> >       if (a.month, a.day) < (b.month, b.day): # tuple comparison
> >           y -= 1
> >       return y
>
> At least it doesn't blow up when b is leapyear-02-29. It just gives the
> wrong answer when a is nonleapyear-02-28. E.g. it gives 0 years
> difference  from 1992-02-29 to 1993-02-28 instead of 1.

I believe you're mistaken (but feel free to correct me), my grandmother
is born on Feb 29 and a quick call to my dad verified that they
celebrated it the day after the 28th (unless Mar 1 was a Monday ;-).
http://timeanddate.com/date/duration.html also seem to agree with my
current understanding, just as a datapoint if nothing else.

-- bjorn




More information about the Python-list mailing list