You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Add .replace() to timedelta to be consistent with date and datetime
Currently, both date and datetime have a .replace() method and supports the __replace__ protocol
For unclear reasons, timedelta doesn't follow suit.
In [1]: from datetime import datetime, date, timedelta
In [2]: d = datetime.now()
In [3]: d.replace(day=1)
Out[3]: datetime.datetime(2025, 6, 1, 16, 50, 54, 282957)
In [4]: import copy
In [6]: copy.replace(d, second=1)
Out[6]: datetime.datetime(2025, 6, 5, 16, 50, 1, 282957)
In [7]: d = date.today()
In [8]: d.replace(day=1)
Out[8]: datetime.date(2025, 6, 1)
In [10]: copy.replace(d, day=1)
Out[10]: datetime.date(2025, 6, 1)
In [11]: t = timedelta(seconds=100)
In [12]: copy.replace(t, second=1)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[12], line 1
----> 1 copy.replace(t, second=1)
File ~/miniconda3/envs/core-313/lib/python3.13/copy.py:305, in replace(obj, **changes)
303 func = getattr(cls, '__replace__', None)
304 if func is None:
--> 305 raise TypeError(f"replace() does not support {cls.__name__} objects") 306 return func(obj, **changes)TypeError: replace() does not support timedelta objects# Add a code block here, if required
Has this already been discussed elsewhere?
No response given
Links to previous discussion of this feature:
No response
The text was updated successfully, but these errors were encountered:
What should td.replace(seconds=250) return -- timedelta(minutes=5, seconds=250) or timedelta(seconds=250)? What should td.replace(minutes=3) return -- timedelta(minutes=3, seconds=102), timedelta(minutes=3, seconds=42) or timedelta(seconds=180)? If the last option is the answer in both cases, how does it differ from just using the timedelta constructor? And I haven't even touched on the issue of days and microseconds, which complicates things even more.
Uh oh!
There was an error while loading. Please reload this page.
Feature or enhancement
Proposal:
Requirements:
__replace__
support fortimedelta
.replace()
totimedelta
to be consistent withdate
anddatetime
Currently, both
date
anddatetime
have a.replace()
method and supports the__replace__
protocolFor unclear reasons,
timedelta
doesn't follow suit.Has this already been discussed elsewhere?
No response given
Links to previous discussion of this feature:
No response
The text was updated successfully, but these errors were encountered: