[Datetime-SIG] Timeline arithmetic?
Tim Peters
tim.peters at gmail.com
Sat Sep 5 04:02:36 CEST 2015
[Chris Barker]
> I dont get that at all -- a Period recurrence lib needs to know all sorts of
> stuff about the timezone, and other things, like days of the week. And it
> needs to be able to do "timeline arithmetic", but it would presumable be
> able to remove and tack back on a tzinfo object all on it's own -- i.e. so
> the arithmetic it wants.
Chris, I think you must mean something quite different by "period
recurrence" than others mean. I like the term "calendar operation"
better. Things like "2pm the 3rd Monday of every 5th month". Nobody
ever means, for example, "but change it to 1pm or maybe 3pm if
daylight time starts or ends". They always mean "2pm on the local
clock, regardless of how often or by how much politicians change the
local clock". timeline arithmetic is horrid for this kind of thing.
It's only if you _do_ use timeline arithmetic for calendar operations
that you need to know about timezone rules, in order to _undo_ the
damage timeline arithmetic did. Ignore the timezone entirely (classic
arithmetic), and it's much easier.
Indeed, if you added a dateutil relativedelta to a datetime with a
tzinfo that _did_ force timeline arithmetic, nothing would blow up but
the result could be dead wrong, and _would_ most likely be dead wrong
whenever the input and result had an odd number of DST transitions
between them.
You can, of course, look at its source. While it could be rewritten
to force classic arithmetic, it doesn't bother now. The relativedelta
type's implementation never even checks to see whether a datetime
input _has_ a tzinfo. It doesn't need to care now. It builds the
result out of a mix of replacing some fields in the datetime (like the
year and/or month, if required), and leaves the rest to one or more
uses of Python's datetime + timedelta arithmetic. For example, "3rd
Monday of the month" reduces to dateutil figuring out when the first
Monday of the month is, then adding a Python timedelta with days=[the
number needed to get to the first Monday of the month] and weeks=2.
dateutil has lots of its own logic to implement, but it currently
relies on that classic arithmetic is always in effect, and is spared
from needing to duplicate the logic already implemented by Python's
timedelta arithmetic. The latter is a very useful building block for
these kinds of applications, directly handling all (& only) the units
needed in "calendar operations" for which there is no argument about
"the best" meaning.
> But maybe if I tried to implement one (which I will never do) , I'd see you
> point. Bu tin any case, doesn't dateutils already provide this?
What a coincidence! I must have read your mind ;-)
More information about the Datetime-SIG
mailing list