Why does datetime.timedelta only have the attributes 'days' and 'seconds'?

Chris Angelico rosuav at gmail.com
Sat Apr 16 15:30:19 EDT 2022


On Sun, 17 Apr 2022 at 03:52, Peter J. Holzer <hjp-python at hjp.at> wrote:
>
> On 2022-04-17 02:46:38 +1000, Chris Angelico wrote:
> > On Sun, 17 Apr 2022 at 02:45, Peter J. Holzer <hjp-python at hjp.at> wrote:
> > > On 2022-04-17 02:14:44 +1000, Chris Angelico wrote:
> > > > So which one is it? Which one do you get when you add days=7 to a datetime?
> > >
> > > For adding a datetime and timedelta I think the answer is clear.
> > > But subtracting two datetimes is ambiguous.
> > >
> >
> > But if the difference between two datetimes is a timedelta, then
> > surely adding a timedelta to a datetime should give the other
> > datetime?
>
> Not necessarily. You might compute the difference for another purpose.
> If you compute a change rate from two gauge readings you would compute
> something like (r1 - r0) / (t1 - t0). You don't intend to add (t1 - t0)
> to any timestamp, so that property would be irrelevant. However, you do
> want something which can be used in a division and which has a
> consistent unit (so one could argue that you don't want a timedelta
> object at all, but a floating point number).
>

True, but logically, it's hard to explain arithmetic when (x - y) + x
!= y. ( And yes, I'm aware that floats can violate that, but the
discrepancy isn't a good thing.)

Your example definitely wants to be measured in UTC, though. It wants
to ignore silly changes of clocks, and just show the amount of time
that passed.

ChrisA


More information about the Python-list mailing list