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

Chris Angelico rosuav at gmail.com
Sat Apr 16 12:14:44 EDT 2022


On Sun, 17 Apr 2022 at 02:03, Peter J. Holzer <hjp-python at hjp.at> wrote:
>
> On 2022-04-16 14:22:04 -0000, Jon Ribbens via Python-list wrote:
> > timedelta(days=1) is 24 hours (as you can check by
> > calling timedelta(days=1).total_seconds() ),
>
> It shouldn't be. 1 Day is not 24 hours in the real world.
>
> > but d1 is 25 hours later
> > than 'd'. If we do the calculations in UTC instead, it works correctly:
> >
> >     >>> print((d.astimezone(UTC) + datetime.timedelta(days=1)).astimezone(LOS_ANGELES))
> >     2020-11-01 11:00:00-08:00
> >
> > It seems that Python is assuming that if the tzinfo attributes of two
> > datetimes are the same,
>
> There is only one datetime in your examples.
>
> > then it can pretend timezones don't exist and do 'naive' arithmetic.
>
> On the contrary. When a datetime is timezone aware, it must use that
> timezone's rules. Adding one day to a datetime just before a DST switch
> must add 23 or 25 hours, not 24. This is NOT naive.
>
> (There is an ambiguity, though: Should 2021-03-27T12:00 CEST -
> 2021-03-26T12:00 CET return 1 day or 25 hours? Both results are correct,
> and depending on context you might prefer one or the other).
>

That's exactly the problem. A day IS 24 hours *and* it is the time
period required for you to get to the same clock on the following
date. It's fundamentally ambiguous.

Let's take this out of Python altogether for a moment. Imagine that
it's 9AM Thursday. You say to your friend, hey, let's meet up again,
same time next week. Are you planning to meet 168 hours later, or at
9AM the following Thursday?

OF COURSE you mean 168 hours later. That's what "next week" means.

OF COURSE you're meeting at 9AM the following Thursday. That's what
"next week" means.

And they can't both be true if DST is changing.

So which one is it? Which one do you get when you add days=7 to a datetime?

ChrisA


More information about the Python-list mailing list