1 回答
TA贡献1820条经验 获得超10个赞
日期20-07-2020-与您的意思day-month-year不匹配。你的and顺序错误。所以你必须使用而不是%m-%d-%Ymonth-day-yeardaymonth%d-%m%m-%d
顺便说一句:你必须计算stop - start而不是start - stop
from datetime import datetime
start = '20-07-2020 11:00:00'
stop = '20-07-2020 13:30:00'
format_date = "%d-%m-%Y %H:%M:%S"
dt_start = datetime.strptime(start, format_date)
dt_stop = datetime.strptime(stop, format_date)
duration = dt_stop - dt_start
print(f'Start: {dt_start}, Stop: {dt_stop}')
print(duration)
结果
Start: 2020-07-20 11:00:00, Stop: 2020-07-20 13:30:00
2:30:00
要格式化它,您需要获取总秒数并计算小时、分钟、秒
rest = duration.total_seconds()
hours = int(rest // (60*60))
rest = rest % (60*60)
minutes = int(rest // 60)
seconds = int(rest % 60)
print(f"{hours} hours, {minutes} minutes, {seconds} seconds")
结果
2 hours, 30 minutes, 0 seconds
或者你必须将持续时间转换为字符串然后拆分它
hours, minutes, seconds = str(duration).split(':')
print(f"{hours} hours, {minutes} minutes, {seconds} seconds")
结果
2 hours, 30 minutes, 00 seconds
顺便说一句:当你转换duration为字符串时,它会运行类似于我的计算的代码total_seconds——我在源代码中检查过这个。
添加回答
举报