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

Random832 random832 at fastmail.com
Tue Apr 19 18:10:11 EDT 2022


On Tue, Apr 19, 2022, at 07:11, Loris Bennett wrote:
> I now realise that timedelta is not really what I need.  I am interested
> solely in pure periods, i.e. numbers of seconds, that I can convert back
> and forth from a format such as

A timedelta *is* a pure period. A timedelta of one day is 86400 seconds.

The thing you *think* timedelta does [making a day act as 23 or 25 hours across daylight saving boundaries etc], that you *don't* want it to do, is something it *does not actually do*. I don't know how this can be made more clear to you.

timedelta is what you need. if you think it's not, it's because you're using datetime incorrectly.

The real problem is that naive datetime objects [without using either a fixed timezone offset like the built-in utc, or a library like pytz] are not fit for any purpose.

If you use pytz correctly [which is unfortunately awkward due to leaky abstractions and mismatches between the datetime model works and how most people expect datetimes with timezones to work], you will indeed get 24 hours from timedelta(days=1)

>>> et = pytz.timezone('America/New_York')
>>> et.normalize(et.localize(datetime.datetime(2022,3,12,12,0,0)) + datetime.timedelta(days=1))
datetime.datetime(2022, 3, 13, 13, 0, tzinfo=<DstTzInfo 'America/New_York' EDT-1 day, 20:00:00 DST>)

you can see here that 2022-03-12T12:00-0500 + timedelta(days=1) correctly becomes 2022-03-13T13:00-0400, 24 hours later.

As far as I know, Python doesn't even have a way to represent "1 day" [or 1 month, 1 year] as a context-dependent-length interval (the thing you think timedelta does), at least not within the standard library and the datetime model.

>   11-22::44:55
>
> (These are the lengths of time a job has run on an HPC system - leap
> seconds and time zones are of no relevance).
>
> It is obviously fairly easy to rustle up something to do this, but I am
> surprised that this is not baked into Python (such a class also seems to
> be missing from R).  I would have thought that periods crop up all over
> the place and therefore formatting as strings and parsing of string
> would be supported natively by most modern languages.  Apparently not.
>
> Cheers,
>
> Loris
>
> -- 
> This signature is currently under construction.
> -- 
> https://mail.python.org/mailman/listinfo/python-list


More information about the Python-list mailing list