[Python-Dev] Change the repr for datetime.timedelta (was Re: Asynchronous context manager in a typical network server)

Guido van Rossum guido at python.org
Sun Dec 20 21:00:20 EST 2015


On Sun, Dec 20, 2015 at 5:00 PM, Alexander Belopolsky <
alexander.belopolsky at gmail.com> wrote:

>
> On Sun, Dec 20, 2015 at 5:28 PM, Chris Angelico <rosuav at gmail.com> wrote:
>
>> > A helpful trivia: a year is approximately π times 10 million seconds.
>>
>> Sadly doesn't help here, as the timedelta for a number of years looks
>> like this:
>>
>> >>> datetime.timedelta(days=365*11)
>> datetime.timedelta(4015)
>>
>>
> The original issue was how long is a million seconds.  The bit of trivia
> that I suggested helps to establish that it cannot be a multiple of years.
>

But it's entirely arbitrary, which makes it not that easy to remember.


> Would there be value in changing the repr to use keyword arguments?
>>
>
> I don't think translating from seconds to years will be any simpler with
> any alternative  repr,
>

Well it would have saved me an embarrassing moment -- I typed
`datetime.timedelta(seconds=1e6)` at the command prompt and when the
response came as `datetime.timedelta(11, 49600)` I mistook that as 11 years
(I was in a hurry and trying hard not to have to think :-).


> but I would really like to see a change in the repr of negative timedeltas:
>
> >>> timedelta(minutes=-1)
> datetime.timedelta(-1, 86340)
>
> And str() is not much better:
>
> >>> print(timedelta(minutes=-1))
> -1 day, 23:59:00
>
> The above does not qualify as a human readable representation IMO.
>

I'm sure that one often catches people by surprise. However, I don't think
we can fix that one without also fixing the values of the attributes -- in
that example days is -1 and seconds is 86340 (which will *also* catch
people by surprise). And changing that would be much, much harder for
backwards compatibility reasons-- we'd have to set days to 0 and seconds to
-60, and suddenly we have a much murkier invariant, instead of the crisp

    0 <= microseconds < 1000000
    0 <= seconds < 60

(There is no such invariant for days -- they hold the sign bit.)

In essence, you'd have to look at all three attributes to figure out on
which side of 0 is was (or think of the right way to do it, which is to
compare to timedelta(0)). I might still go for it, if it wasn't too late by
over a decade (as Tim says).

-- 
--Guido van Rossum (python.org/~guido)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-dev/attachments/20151220/d79db24a/attachment.html>


More information about the Python-Dev mailing list