[Datetime-SIG] PEP-0500 (Alternative datetime arithmetic) Was: PEP 495 ... is ready ...

Tim Peters tim.peters at gmail.com
Wed Aug 19 17:55:55 CEST 2015


[Guido ]
> Yes, that's the right way to define it (and PEPs should primarily concern
> themselves with crisp definitions).
>
> Isn't it so that you could get timeline arithmetic today by giving each
> datetime object a different tzinfo object?

For datetime - datetime subtraction, yes, and that's always been so.

The Python code for that is mildly instructive here, since it doesn't
actually convert anything to a UTC timezone, nor does it do any
arithmetic directly _on_ a datetime:

    def __sub__(self, other):
        ...
        days1 = self.toordinal()
        days2 = other.toordinal()
        secs1 = self._second + self._minute * 60 + self._hour * 3600
        secs2 = other._second + other._minute * 60 + other._hour * 3600
        base = timedelta(days1 - days2,
                         secs1 - secs2,
                         self._microsecond - other._microsecond)
        if self._tzinfo is other._tzinfo:
            return base
        myoff = self.utcoffset()
        otoff = other.utcoffset()
        if myoff == otoff:
            return base
        if myoff is None or otoff is None:
            raise TypeError("cannot mix naive and timezone-aware time")
        return base + otoff - myoff

It's "for speed" that it uses timedelta arithmetic, bashing the
datetimes into timedelta's days+seconds+microseconds format first
(which is equivalent to using "bigint" timestamps counting
microseconds since 1 Jan 1!)..  Then instead of converting zones, it
just adjusts the result (when appropriate) by the difference between
the inputs' UTC offsets.

So the kinds of things PEP 500 shows are, appropriately, the simplest
ways of spelling out the intents.  The implementations may look very
different - provided they behave the same way.


More information about the Datetime-SIG mailing list