YADTR (Yet Another DateTime Rant)

Skip Montanaro skip at pobox.com
Wed Mar 26 14:37:06 CET 2014

It's not clear to me what the correct str should be. I think the
desired format changes depending on the relative magnitude of the
timedelta object. For small values (less than a day), I agree, the
behavior is, well, odd.  You can get around that easily enough:

>>> d = datetime.timedelta(seconds=-2)
>>> str(d)
'-1 day, 23:59:58'
>>> "-%s" % -d

The problem gets more challenging once you get into magnitudes > one

>>> e = datetime.timedelta(days=-4, seconds=3605)
>>> e
datetime.timedelta(-4, 3605)
>>> print e
-4 days, 1:00:05

Hmmm... It's printing just what we said, negative four days, positive
one hour, five minutes. Let's try the trick from above:

>>> print -e
3 days, 22:59:55
>>> "-%s" % -e
'-3 days, 22:59:55'

Ehhh... not so much.  The fundamental problem here is the scope of the
minus sign. My trick assumes it applied to the entire string
representation.  It's clear that in the first case that it applies to
the entire displayed value, as there are no spaces. In the second
case, we know it only applies to the days, because it's spitting back
exactly what I fed the constructor.  So, that means the simple minus
sign trick won't work in the third case. Complicating things are that
timedelta objects are normalized internally so that the seconds field
is always non-negative (explaining the weird "-1 day, 23:59:58" string
representation of the first case).

I'm not sure there's a one-size-fits-all solution to this problem. For
offsets of less than a day, I suppose you could argue that the string
representation shouldn't include the "-1 day" bit. Beyond that, I
think you kind of have to live with what it gives you.


More information about the Python-list mailing list