Skip to content

Add __replace__ protocol support to timedelta #135195

Closed as not planned
Closed as not planned
@mpkocher

Description

@mpkocher

Feature or enhancement

Proposal:

Requirements:

  • Add __replace__ support for timedelta
  • 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

Metadata

Metadata

Assignees

No one assigned

    Labels

    extension-modulesC modules in the Modules dirpendingThe issue will be closed if no feedback is providedstdlibPython modules in the Lib dirtype-featureA feature request or enhancement

    Projects

    Status

    Done

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions