python - 超过 24 小时的日期时间格式

标签 python datetime

我正在尝试添加时间并将输出作为 hh:mm:ss,但是当 datetime 超过 24 小时时,它将变为 x Days, hh:mm:ss。是否只有 hh:mm:ss 大于 24 小时?

import datetime
from datetime import timedelta

# intro
print("Welcome to TimeCalc")

print("Calculating Durations")

clear = True
while clear == True:
    # first input
    firstNumber = True
    while firstNumber == True:
        time_1 = input("Please enter a time [hh:mm:ss] including 0s: ")
        if len(time_1) > 0 and len(time_1) >= 8 and time_1[-6] == ":" and time_1[-3] == ":" and int(time_1[-5:-3]) < 60 and int(time_1[-2:]) < 60:
            hours_1 = time_1[:-6]
            minutes_1 = time_1[-5:-3]
            seconds_1 = time_1[-2:]
            hours_1 = int(hours_1)
            minutes_1 = int(minutes_1)
            seconds_1 = int(seconds_1)
            firstNumber = False
        else:
            print("Invalid Syntax")
    time_1 = datetime.timedelta(hours=hours_1, minutes=minutes_1, seconds=seconds_1)

    cont = True
    while cont == True:
        # second input
        secondNumber = True
        while secondNumber == True:
            time_2 = input("Please enter a time to add [hh:mm:ss] including 0s: ")
            if len(time_2) > 0 and len(time_2) >= 8 and time_2[-6] == ":" and time_2[-3] == ":" and int(time_2[-5:-3]) < 60 and int(time_2[-2:]) < 60:
                hours_2 = time_2[:-6]
                minutes_2 = time_2[-5:-3]
                seconds_2 = time_2[-2:]
                hours_2 = int(hours_2)
                minutes_2 = int(minutes_2)
                seconds_2 = int(seconds_2)
                secondNumber = False
            else:
                print("Invalid Syntax")
        time_2 = datetime.timedelta(hours = hours_2, minutes = minutes_2, seconds = seconds_2)

        total = time_1 + time_2
        print("The total duration is: " + str(total))

        # continue, clear, or exit
        choice = input("Continue: Y | Clear: N | Exit: X: ")
        if choice == "Y" or choice == "y":
            time_1 = total
        elif choice == "N" or choice == "n":
            cont = False
        elif choice == "X" or choice == "x":
            quit()

最佳答案

total变量之后,你能不能试试把这段代码,也许这不是一个 super 解决方案,但它有效

seconds = int(total.total_seconds())
minutes, seconds = divmod(seconds, 60)
hours, minutes = divmod(minutes, 60)

print("The total duration is: {h:02d}:{m:02d}:{s:02d}".format(h=hours,                                                                 
                                                        m=minutes, s=seconds))

关于python - 超过 24 小时的日期时间格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50422329/

相关文章:

python - 为什么程序执行时间和以前一样?

Python 应用配置最佳实践

java - 如何使用 Internet 时间服务器获取时间?

python - 在 Pandas 多索引中选择日期范围的正确方法是什么?

sql - Hive:日期范围未从表中获取数据

python - 正则表达式模式以匹配 python 中的日期时间

python 日期时间查询

python - 在Python中创建响应式(Reactive)迭代器的策略是什么?

python setup.py目录权限

带有图形数据库的 python 图形工具库