为了账号安全,请及时绑定邮箱和手机立即绑定

减去两次以获得持续时间 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 关注
  • 184 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信