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

Peter J. Holzer hjp-python at hjp.at
Sat Apr 16 15:32:24 EDT 2022


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.

        hp

-- 
   _  | Peter J. Holzer    | Story must make more sense than reality.
|_|_) |                    |
| |   | hjp at hjp.at         |    -- Charles Stross, "Creative writing
__/   | http://www.hjp.at/ |       challenge!"
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 833 bytes
Desc: not available
URL: <https://mail.python.org/pipermail/python-list/attachments/20220416/a39e29e2/attachment.sig>


More information about the Python-list mailing list