计算开始时间、当前时间和结束时间之间的百分比 - python

Calculate percentage between startTime, currentTime and endTime - python

我想做一个进度条。要实现这一点,我首先需要百分比。

比如我看电影。我知道电影什么时候开始 (startTime) 什么时候结束 (endTime)。

startTime = "09:40" currentTime = "11:52" endTime = "13:05"

所以我需要计算当前的播放百分比。

感谢任何帮助,谢谢!

from datetime import datetime

timefmt = "%H:%M"
startTime = datetime.strptime("09:40", timefmt)
currentTime = datetime.strptime("11:52", timefmt)
endTime = datetime.strptime("13:05", timefmt)

ratio = (currentTime - startTime) / (endTime - startTime)
print(f"{ratio:5.2%}")

您可以将字符串解析为 datetime object; those can be subtracted (which will return a timedelta 对象)。

然后只需使用 sting 格式即可打印百分比。


为了在 python 2.7 中工作,您需要在 timedelta 对象上调用 total_seconds() 并将 f-string 替换为 str.format:

ratio = (currentTime - startTime).total_seconds() / (endTime - startTime).total_seconds()
print("{:5.2%}".format(ratio))

可以使用答案中已经提到的 datetime 模块来完成,但这是一种更 brute-force 或通用的方法,即使时间在 HH:MM:SS 格式

startTime = "09:40" 
currentTime = "11:52" 
endTime = "13:05"

def changeToMin(time):
    arr = list(map(int, time.split(':')))
    seconds = 0
    for n,i in enumerate(arr):
        seconds += i*60**(len(arr)-n-1)
    return seconds
    
def precentage(start, end, current):
    return (current-start)*100/(end-start)
    
print(precentage(changeToMin(startTime), changeToMin(endTime), changeToMin(currentTime)))