Quick Python question

Kent Borg kentborg-KwkGvOEf1og at public.gmane.org
Thu Oct 8 12:52:20 EDT 2009


Jerry Feldman wrote:
> Basically, given a date, I need to add years to that date.

The obvious thing to do is use a timedelta object--except timedelta
objects don't provide for "years".  The problem is that a "year" is
ambiguous.  If the "year" you are interested in is a time duration, then
a timedelta will work, put in your duration--365 days, or 365 and a
quarter days, or something else...

>  One way to do
> it is:
>
> from datetime import date
> d = date.today() # initialize d to some date
> d = date(d.year + 1, d.month, d.day)
>
> In the above case I'm setting a date object d to todays date, then
> advancing it to the next year. Is there a more elegant or efficient way
> of doing this in Python. 

If you want to increment the year field, then I think you are doing the
right thing.


> The above method certainly works fine except for February 29th, which is not important. 
>   

In that case the answer is ambiguous again.  I don't know what the right
answer is, I presume that there are canonical right answers for
different problem domains.  If you try to defiine "d = date(2009, 2,
29)" you will get "ValueError: day is out of range for month", and
depending on what is your correct behavior, catch that error and fix
there.  (I think it is probably wrong to initially special case February
29th--let the system complain first and fix it then.  Verify the error
was caused by something you understand and then fix it appropriately)

Python cannot do the right thing for you for free because the answer is
ambiguous.  (MS Excel goes to great efforts to do the right thing for
dates and times and occasionally wreaks havoc doing so, scientific
studies have been ruined because Excel took neutral data and started
formatting it "the right way".)

Reminds me of another old story: Some old English great house was using
Sybase (I think) to catalogue their collection of stuff but Sybase
wouldn't offer a date type that went back nearly far enough.  The
problem was the switchover from Gregorian to Julian dates, it happened
at different times in different places, so the database refused to do
dates that were ambiguous and they had to roll their own for anything
that predated the Russian revolution.

Time seems simple, it comes in seconds and we know how big they are, but
once humans start counting up and converting to larger units and being
creative in how they do so, it is an unholy mess.  Ever listened to WWV
count out a 61-second minute?  Freaky.


-kb






More information about the Discuss mailing list