【问题标题】:Python 'hhmmss' time calculationPython 'hhmmss' 时间计算
【发布时间】:2021-08-26 06:21:43
【问题描述】:

我想计算 'hhmmss' 格式。

例如,'082358'(=08:23:58) 加上 3 秒,所以我可以得到 '082401'。

Function(time, sec):  # Function('082358', 3)
     time += sec
     return time      # return '082401'

我该怎么做

  1. 将字符串反转为时间
  2. 计算
  3. 再次将时间反转为字符串('hhmmss' 格式)

【问题讨论】:

  • 嗨,詹姆斯,欢迎来到 SO。我想说的是 StackOverflow 问题应该显示您已经尝试过的内容。

标签: python datetime time


【解决方案1】:

使用datetime.timedelta和strftime,strptime来自datetime.datetime

from datetime import datetime, timedelta

def time_str_delta(time_str, sec):
    _time = datetime.strptime(time_str, '%H%M%S')
    return (_time + timedelta(seconds=sec)).strftime('%H%M%S')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-02-04
    • 1970-01-01
    • 1970-01-01
    • 2017-08-26
    • 2010-12-26
    • 2011-01-23
    • 2015-01-06
    • 2017-08-24
    相关资源
    最近更新 更多