Problem with dates and daylight savings...

Peter Hansen peter at engcorp.com
Mon Apr 12 12:31:26 EDT 2004


John Taylor wrote:
> I was wondering if some one could explain this anomaly.  I wrote a program to add/subtract
> dates.  For example,
> 
> ./ComputeDay.py 2004/04/12 -7 %Y/%m/%d
> 2004/04/05
> 
> Here is the anomaly....
> ./ComputeDay.py 2004/04/12 -8 %Y/%m/%d
> 2004/04/03
> 
> I would have thought this would have returned the 4th.  I have a feeling that daylight savings
> has something to do with this, as the time changed on the 3rd.
> Can someone explain this?  How can I correct this problem?

Doing date math using seconds is highly error-prone and frustrating.

The way to correct this is to use the datetime module:

c:\>python
Python 2.3.3 (#51, Dec 18 2003, 20:22:39) [MSC v.1200 32 bit (Intel)] on 
win32
 >>> from datetime import datetime, timedelta
 >>> d = datetime(2004,4,12)
 >>> d
datetime.datetime(2004, 4, 12, 0, 0)
 >>> d - timedelta(days=8)
datetime.datetime(2004, 4, 4, 0, 0)

You might be right about the daylight savings time thing, but who
cares? ;-)  The datetime module is the right tool for the job here
and it gets the correct result.

-Peter



More information about the Python-list mailing list