-1

My initial string looks like following:

a1 = "06:00:00"
a2 = "01:00:00"

I want to set the time back by two hours.

How to get the following output (in string format)?

a1_new = "04:00:00"
a2_new = "23:00:00"
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
qwertzi
  • 31
  • 4

7 Answers7

1
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'
Mako212
  • 6,787
  • 1
  • 18
  • 37
1

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))
Lukasz Wiecek
  • 414
  • 2
  • 8
1

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
SunAwtCanvas
  • 1,261
  • 1
  • 13
  • 38
1

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)
XxJames07-
  • 1,833
  • 1
  • 4
  • 17
1

Convert to datetime, subtract timedelta, convert to string.

from datetime import datetime, timedelta

olds = ["06:00:00", "01:00:00"]
objs = [datetime.strptime(t, "%H:%M:%S") - timedelta(hours=2) for t in olds]
news = [t.strftime("%H:%M:%S") for t in objs]
theherk
  • 6,954
  • 3
  • 27
  • 52
1

If your strings are always going to follow that exact format and you don't want to use datetime, here's a different way to do it: You could split the strings by their colons to isolate the hours, then work on them that way before joining back to a string.

a1 = "06:00:00"

parts = a1.split(":")             # split by colons
hour = (int(parts[0]) - 2) % 24   # isolate hour, convert to int, and subtract hours, and clamp to our 0-23 bounds
parts[0] = f"{hour:02}"           # :02 in an f-string specifies that you want to zero-pad that string up to a maximum of 2 characters

a1_new = ":".join(parts)          # rejoin string to get new time

If there's any uncertainty in the format of the string however, this completely falls apart.

1

You can use datetime and benefit from the parameters of datetime.timedelta:

from datetime import datetime, timedelta

def subtime(t, **kwargs):
    return (datetime.strptime(t, "%H:%M:%S") # convert to datetime
            - timedelta(**kwargs)  # subtract parameters passed to function 
            ).strftime("%H:%M:%S") # format as text again

subtime('01:00:00', hours=2)
# '23:00:00'

subtime('01:00:00', hours=2, minutes=62)
# '21:58:00'
mozway
  • 194,879
  • 13
  • 39
  • 75