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

Jon Ribbens jon+usenet at unequivocal.eu
Sat Apr 16 09:47:32 EDT 2022


On 2022-04-16, Peter J. Holzer <hjp-python at hjp.at> wrote:
> On 2022-04-14 15:22:29 -0000, Jon Ribbens via Python-list wrote:
>> On 2022-04-14, Paul Bryan <pbryan at anode.ca> wrote:
>> > I think because minutes and hours can easily be composed by multiplying
>> > seconds. days is separate because you cannot compose days from seconds;
>> > leap seconds are applied to days at various times, due to
>> > irregularities in the Earth's rotation.
>>
>> That's an argument that timedelta should *not* have a 'days' attribute,
>> because a day is not a fixed number of seconds long (to know how long
>> a day is, you have to know which day you're talking about, and where).
>
> Which is exactly why timedelta *must* have separate fields for seconds,
> days and months. You can't simply express the larger units as
> multiples of the smaller units, so they have to be stored separately for
> date arithmetic to work.

That's impossible unless you redefine 'timedelta' from being, as it is
now, a fixed-length period of time, to instead being the difference
between two specific dates and times in specific timezones. Days and
months have different lengths depending on when and where you are.

>> It's an undocumented feature of timedelta that by 'day' it means '86400
>> seconds'.
>
> I'd call that a bug, not a feature:

It's the only possible way of implementing it, so it can't be a bug.
The documentation could be better though.

>>>> from datetime import datetime, timedelta
>>>> t0 = datetime.fromisoformat("2022-03-26T12:00").astimezone()
>>>> t0
> datetime.datetime(2022, 3, 26, 12, 0, tzinfo=datetime.timezone(datetime.timedelta(seconds=3600), 'CET'))
>>>> d = timedelta(days=1)
>>>> t1 = t0 + d
>>>> t1
> datetime.datetime(2022, 3, 27, 12, 0, tzinfo=datetime.timezone(datetime.timedelta(seconds=3600), 'CET'))
>>>> t1.isoformat()
> '2022-03-27T12:00:00+01:00'
>
> Python missed the switch to DST here, the timezone is wrong.

Because you didn't let it use any timezone information. You need to
either use the third-party 'pytz' module, or in Python 3.9 or above,
the built-in 'zoneinfo' module.


More information about the Python-list mailing list