Home > Net >  How to change the date of time instance using python?
How to change the date of time instance using python?

Time:12-23

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'

CodePudding user response:

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

CodePudding user response:

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.

  • Related