[Datetime-SIG] PEP-0500 (Alternative datetime arithmetic) Was: PEP 495 ... is ready ...
tim.peters at gmail.com
Thu Aug 20 02:46:00 CEST 2015
> /// let me substantiate my claim about 10x performance penalty.
> $ python3 -m timeit -s "from datetime import datetime, timezone; t = datetime.now(timezone.utc); l = t.astimezone()" "l - t"
> 1000000 loops, best of 3: 0.448 usec per loop
> $ python3 -m timeit -s "from datetime import datetime, timezone; t = datetime.now(); l = t" "l - t"
> 10000000 loops, best of 3: 0.0444 usec per loop
> Currently, subtracting aware datetimes with the same tzinfo incurs no
> $ python3 -m timeit -s "from datetime import datetime, timezone; t = datetime.now(timezone.utc); l = t" "l - t"
> 10000000 loops, best of 3: 0.0436 usec per loop
> With PEP 500, we can have timeline arithmetic without the overhead of two
> round trips to tzinfo. I will be happy if someone would demonstrate how to
> achieve the same by simpler means.
In general, I agree timeline arithmetic "belongs in" tzinfo objects.
As you've said elsewhere, the tzinfo interface gives general datetime
code a microscopically tiny understanding of how a given timezone
works; in effect, it can only ask what the total UTC offset and DST
offset are at a single microsecond in local time, or what a single
microsecond in UTC time looks like in local time. Code outside the
tzinfo can't _deduce_ anything more generally applicable from any of
that; code inside the tzinfo knows everything about how the timezone
But in the specific case above, I'd call the specter of slowdowns a
QOI (quality of implementation) issue. For
(including UTC), classic and timeline arithmetic are exactly the same
thing. A high-quality wrapping of timezone info should take advantage
of that, by _not_ using whatever spelling of "this tzinfo object wants
timeline arithmetic" is introduced for such timezones. In which case,
the naive arithmetic shortcuts will continue to be used for such
I expect this will be crucial for timezone.utc (should be a
requirement), so that code implementing fancier stuff can _rely_ on
that doing arithmetic on UTC instances won't fall into the kinds of
infinite regress Lennart got buried under, and without needing endless
annoying and time-consuming dances to strip and re-attach the tzinfo
object (to force classic arithmetic).
More information about the Datetime-SIG