Python Glossary Русский

all Python 3datetimefunction

datetime.datetime.replace()

datetime methods

Creates a new datetime/date/time object with some fields replaced. The original is not changed — datetime is immutable.

Syntax

dt.replace(year=, month=, day=, hour=, minute=, second=, microsecond=, tzinfo=)

The classic trap is replace(tzinfo=...): it does not convert anything, it just relabels the same wall-clock time, so 10:00 stays 10:00. Use astimezone() when you actually want the time recomputed for another zone. Substituting a date that does not exist (day=31 in February) raises ValueError instead of clamping to the end of the month.

Examples

from datetime import datetime
now = datetime(2024, 6, 17, 10, 30)
new = now.replace(hour=0, minute=0, second=0)  # начало дня
print(new)  # 2024-06-17 00:00:00
# заменить только год
next_year = now.replace(year=2025)

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy