In Python, you can replace parts of a datetime using the replace() method. This method returns a new datetime object with the specified parts replaced. Here's an example:
from datetime import datetimedt = datetime(2022, 3, 14, 13, 23, 45)new_dt = dt.replace(year=2023, month=4, day=15)print(dt) # 2022-03-14 13:23:45print(new_dt) # 2023-04-15 13:23:45 |
In this example, we first create a datetime object representing March 14, 2022 at 1:23:45 PM. We then call the replace() method on this datetime object to create a new datetime object with the year set to 2023, the month set to April, and the day set to 15. The replace() method returns this new datetime object, which we assign to the new_dt variable. Finally, we print both datetime objects to verify that the replacement worked.
Note that when you use the replace() method to replace parts of a datetime, any parts that are not specified are left unchanged. In the example above, we only specified the year, month, and day, so the time components (hours, minutes, and seconds) of the datetime remained the same.