亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

減去兩次以獲得持續時間 Python

減去兩次以獲得持續時間 Python

繁星淼淼 2023-04-18 16:32:12
如何減去兩次以獲得 Python 中的持續時間?我已經使用日期時間嘗試了下面的代碼。輸入開始時間= 20-07-2020 11:00:00輸入停止時間= 20-07-2020 13:30:00我想要的輸出是 2.5 小時或 2 小時 30 分鐘from datetime import datetimeprint("Enter 11:00 13:30 for a task starting at 11am and ending at 1:30 pm.")start=str(input("Enter the start time:"))stop=str(input("Enter the stop time:"))format_date= "%d-%m-%Y %H:%M:%S"duration=datetime.strptime(start,format_date)-datetime.strptime(stop,format_date)durationTask1_start=datetime.strptime(start,format_date)Task1_stop=datetime.strptime(stop,format_date)print(f'Start:{Task1_start}, Stop:{Task1_stop}')
查看完整描述

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——我在源代碼中檢查過這個。


查看完整回答
反對 回復 2023-04-18
  • 1 回答
  • 0 關注
  • 256 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號