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

Chris Angelico rosuav at gmail.com
Sat Apr 16 16:10:47 EDT 2022


On Sun, 17 Apr 2022 at 05:38, 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:
> > > 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? It's just as ambiguous.
>
> To answer the same question in a different way:
>
> No, because the timedelta object is overspecified when applied to a
> specific datetime (when you start at 2022-04-16T21:29, it doesn't matter
> whether you add 7 days or 168 hours) but that extra information matters
> with different starting points. When you subtract two specific
> datetimes, there is no way to extract that extra information. So
> addition and subtraction are not symmetrical.
>

Ah, that's fair. So what you're really saying is that the difference
between two datetimes *isn't* a timedelta, but when we subtract them
and get back a timedelta, we're throwing away information for
simplicity.

ChrisA


More information about the Python-list mailing list