How to subtract 2 hours from time formatted as string [duplicate]

Here you go!

from datetime import datetime, timedelta

a1 = "06:00:00"

x = datetime.strptime(a1, "%H:%M:%S") - timedelta(hours=2, minutes=0)

y = x.strftime("%H:%M:%S")

print(y)

Steps:

  1. Convert HMS into a DateTime Object
  2. Minus 2 hours from this
  3. Convert the result into a String that only contains Hour Minute & Second

from datetime import datetime
from datetime import timedelta

time_fmt = "%H:%M:%S"

a1_new = datetime.strptime(a1, time_fmt) - timedelta(hours = 2)

a1_new = a1_new.strftime("%H:%M:%S")

print(a1_new)

'08:00:00'

I am assuming here that you only need a simple 24-hour clock.

s = "01:00:00"
h, m, s = s.split(":")
new_hours = (int(h) - 2) % 24
result = ':'.join((str(new_hours).zfill(2), m, s))

convert to datetime:

import datetime

a1 = "06:00:00"
obj = datetime.datetime.strptime(a1,"%H:%M:%S")
obj.replace(hour=obj.hour-2) #hours = hours - 2
tostr = obj.hour+":"+obj.min+":"+obj.second
print(tostr)