【问题标题】:How to subtract 2 hours from time formatted as string [duplicate]如何从格式化为字符串的时间中减去 2 小时 [重复]
【发布时间】:2022-01-18 22:28:49
【问题描述】:

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

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

我想把时间往后调两个小时。

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

a1_new = "04:00:00"
a2_new = "23:00:00"

【问题讨论】:

标签: python time


【解决方案1】:

给你!

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. 将结果转换为只包含时分秒的字符串

【讨论】:

    【解决方案2】:
    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'
    

    【讨论】:

      【解决方案3】:

      我在这里假设您只需要一个简单的 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))
      

      【讨论】:

        【解决方案4】:

        转换为日期时间:

        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)
        

        【讨论】:

          【解决方案5】:

          如果您的字符串始终遵循该精确格式并且您不想使用日期时间,则可以使用另一种方法:您可以将用冒号分隔字符串以隔离小时数,然后以这种方式处理它们,然后再加入字符串。

          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
          

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

          【讨论】:

            【解决方案6】:

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

            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]
            

            【讨论】:

              【解决方案7】:

              您可以使用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'
              

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 1970-01-01
                • 2015-10-02
                • 2011-09-15
                • 1970-01-01
                • 2023-04-07
                • 1970-01-01
                • 1970-01-01
                • 2011-06-24
                相关资源
                最近更新 更多