How to change the date of time instance using python?

Question:

I have start_time variable that stores a time string.

start_time = '2022-12-21 22:00:00'

Now Using python i want to change the date of start time to

start_time = '2022-12-28 22:00:00'

I have done this with very ugly approach. Please tell me easy and best way to do that.

I tried with following code.

   #its not string its time instance
   replacing_date = 2022-12-28 00:00:00
   #converting time into string 
   replacing_date = datetime.strptime(replacing_date,'%Y-%m-%d %H:%M:%S')

   replacing_date =replacing_date.split(" ")
   start_time = start_time.split(" ")
   start_time = datetime.strptime(replacing_date[0]+start_time[1],'%Y-%m-%d %H:%M:%S')

Basically i have to change date on many places. It doesn’t seems to be good thing in that case. and it can break if time string format changes.
it can also break if the years or month changes. for example date change to.

start_time = '2023-01-01 22:00:00'
Asked By: Ahmed Yasin

||

Answers:

from datetime import datetime, timedelta
start_time = '2022-12-21 22:00:00'
replacing_date = datetime.strptime(start_time,'%Y-%m-%d %H:%M:%S')
new_time = replacing_date+timedelta(days=7)
print(new_time)

Output:

2022-12-28 22:00:00

use timedelta to change time.

Answered By: vks

You can use datetime.replace(..):

from datetime import datetime

start_time = "2022-12-21 22:00:00"

new_time = datetime.strptime(start_time, "%Y-%m-%d %H:%M:%S").replace(day=28)

print(new_time)

Output:

2022-12-28 22:00:00

Or regexp:

import re

new_time = re.sub(r"d{4}-d{2}-d{2}", "2022-12-28", "2022-12-21 22:00:00", 0)

print(new_time)

Output:

2022-12-28 22:00:00

Answered By: Joan Flotats