0

I would like to add a certain time to a formatted time string in python. For this I tried the following

from datetime import datetime, timedelta

timestemp_Original = '2021-07-13T00:15:00Z'
timestemp_Added1 =  '2021-07-13T00:15:00Z' + timedelta(minutes=15)
timestemp_Added2 = timestemp_Original + datetime.timedelta(hours=0, minutes=15)

but this leads to error messages (I took it from here How to add hours to current time in python and Add time to datetime). Can aynone tell me how to do this?

petezurich
  • 9,280
  • 9
  • 43
  • 57
PeterBe
  • 700
  • 1
  • 17
  • 37
  • Does this answer your question? [Add time to datetime](https://stackoverflow.com/questions/31218508/add-time-to-datetime) Nowhere in the linked questions do they add a `timedelta` to a string. They always _parse_ the string to a `datetime` object using `strptime` and _then_ they add the `timedelta` – Pranav Hosangadi Jul 19 '22 at 13:11
  • But I would like to know if this is directly possible without converting it – PeterBe Jul 19 '22 at 13:14
  • @PeterBe, without converting to `datetime`? – I'mahdi Jul 19 '22 at 13:16
  • No, it is not possible. You're going to have to parse the elements of that string to figure out what needs to be added to what, and if you're doing that you might as well use the `datetime.strptime` function to parse it instead of reinventing the wheel. – Pranav Hosangadi Jul 19 '22 at 13:18

1 Answers1

1

First, You need to convert str to datetime with a specific format of string_date and then use timedelta(minutes=15).

from datetime import datetime, timedelta
timestemp_Original = '2021-07-13T00:15:00Z'
timestemp_Added1 = datetime.strptime(timestemp_Original, "%Y-%m-%dT%H:%M:%SZ") + timedelta(minutes=15)
print(timestemp_Added1)

# If you want to get as original format
print(timestemp_Added1.strftime("%Y-%m-%dT%H:%M:%SZ"))
# 2021-07-13T00:30:00Z

2021-07-13 00:30:00
I'mahdi
  • 23,382
  • 5
  • 22
  • 30