1 回答

TA貢獻(xiàn)1820條經(jīng)驗(yàn) 獲得超10個(gè)贊
日期20-07-2020-與您的意思day-month-year不匹配。你的and順序錯(cuò)誤。所以你必須使用而不是%m-%d-%Ymonth-day-yeardaymonth%d-%m%m-%d
順便說一句:你必須計(jì)算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)
結(jié)果
Start: 2020-07-20 11:00:00, Stop: 2020-07-20 13:30:00
2:30:00
要格式化它,您需要獲取總秒數(shù)并計(jì)算小時(shí)、分鐘、秒
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")
結(jié)果
2 hours, 30 minutes, 0 seconds
或者你必須將持續(xù)時(shí)間轉(zhuǎn)換為字符串然后拆分它
hours, minutes, seconds = str(duration).split(':')
print(f"{hours} hours, {minutes} minutes, {seconds} seconds")
結(jié)果
2 hours, 30 minutes, 00 seconds
順便說一句:當(dāng)你轉(zhuǎn)換duration為字符串時(shí),它會(huì)運(yùn)行類似于我的計(jì)算的代碼total_seconds——我在源代碼中檢查過這個(gè)。
添加回答
舉報(bào)