如何从格式化为字符串的时间中减去 2 小时

How to subtract 2 hours from time formatted as string

我的初始字符串如下所示:

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

我想把时间调慢两个小时。

如何得到下面的输出(字符串格式)?

a1_new = "04:00:00"
a2_new = "23:00:00"
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'

我在这里假设您只需要一个简单的 24 小时时钟。

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

给你!

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)

步骤:

  1. 将 HMS 转换为 DateTime 对象
  2. 距此还有 2 小时
  3. 将结果转换为仅包含时分秒的字符串

转换为日期时间:

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)

转换为日期时间,减去 timedelta,转换为字符串。

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]

如果您的字符串 总是 将遵循 exact 格式并且您不想使用 datetime,这里有一个不同的方法要做到这一点:您可以用冒号分隔字符串以隔离时间,然后在连接回字符串之前以这种方式处理它们。

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

但是,如果字符串的格式存在任何不确定性,这将完全崩溃。

您可以使用 datetime 并受益于 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'