Skip to content

datetime.replace() is very slow #112919

Closed
Closed
@eltoder

Description

@eltoder

Bug report

Bug description:

datetime.replace() is very slow when called with keyword arguments. For example, with python 3.13 from main on my laptop

$ python -m timeit -s "from datetime import datetime; dt = datetime.now()" "dt.replace(microsecond=0)"
500000 loops, best of 5: 501 nsec per loop

For comparison,

$ python -m timeit -s "from datetime import datetime" "datetime.now()"
2000000 loops, best of 5: 150 nsec per loop
$ python -m timeit -s "from datetime import datetime" "datetime(2020, 1, 1, 12, 34, 56, 123456)"
2000000 loops, best of 5: 119 nsec per loop

So calling replace() is over 4x slower than constructing a new datetime from components and over 3x slower than now(), which makes a system call.

CPython versions tested on:

3.9, 3.10, 3.13

Operating systems tested on:

Linux

Linked PRs

Metadata

Metadata

Assignees

No one assigned

    Labels

    3.13bugs and security fixesperformancePerformance or resource usagetype-featureA feature request or enhancement

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions