[Python-Dev] datetime +/- scalars (int, long, float)? (original) (raw)

Kevin Jacobs jacobs@penguin.theopalgroup.com
Tue, 5 Mar 2002 06:58:38 -0500 (EST)


On Tue, 5 Mar 2002, M.-A. Lemburg wrote:

> [Tim] > > The only conclusion I have at this time is that I like datetime > > objects better than real life . > [Guido] > Depends on how you look. If you look at the hour attribute, or call > the isoformat() method, or use str(), you'll see 3pm. If you ask the > ctime() or timetuple() methods, it converts to local time, and you'll > see 2pm or 4pm! [MAL] You should forget about DST if you want a sane implementation. Same for leap seconds.

My datetime objects manage these complexities by layering their implementation. Our base class stores a time since epoch and a timezone offset. It implements all the arithmetic functions based on 1day=24hours and has methods that re-normalize the timezone to a fixed offset after every modifying operation. It also has a translate(tzoffset) function that returns the an adjusted time since epoch with a different timezone offset. This way, our client applications never deal with DST or timezone changes unless they request it.

For calculations that require DST awareness, of which there are a surprising number, we have a datetime sub-class that adds two extra modes:

  1. Fixed tzoffset (from base datetime)

  2. Fixed tzoffset +/- fixed DST adjustment based on current time since epoch (folds in to case 1 after initialization)

  3. Fixed tzoffset +/- dynamic DST based on stored time since epoch (dynamically updates after every mutating date operation)

If someone wants DST and timezone aware time differences, then this is a completely different concept than taking the difference w/r to number of days.

Precisely. Our implementation is sub-optimal in that it can do roughly twice as much work as necessary at times. This is because we layer the DST adjustments on top of the datetime object. The advantage to this approach is that the code is very cleanly segregated between DST agnostic code and DST pathological code.

Just to hint at another problem: you sometimes want to know the time difference of two dates in terms of years, months, days, hours, etc. that is, you are not interested in 86400 second days, but in calendar days or even months. For months you'll run into problems with non-existing days, e.g. for 2002-03-31 - 1 month.

We handle these cases with a business logic layer on top of the DST aware datetime object. It handles exceptions thrown, like BeyondEndOfMonthError, and takes the appropriate action. In the case of BeyondEndOfMonthError, the typical resolution is to set the day to the last day of the month.

-Kevin

-- Kevin Jacobs The OPAL Group - Enterprise Systems Architect Voice: (216) 986-0710 x 19 E-mail: jacobs@theopalgroup.com Fax: (216) 986-0714 WWW: http://www.theopalgroup.com