'Calculate percentage between startTime, currentTime and endTime - python
I want to make a progress bar. To achieve this first i need percentage.
For example i watch the movie. i know when movie starts (startTime) and when ends (endTime).
startTime = "09:40" currentTime = "11:52" endTime = "13:05"
So i need to calculate current percentage of playing.
Any help is appreciated, thanks!
Solution 1:[1]
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%}")
you can parse your strings into a datetime object; those can be subtracted (which will return a timedelta object).
then just use sting formatting in order to print the ratio in percent.
for this to work in python 2.7 you need to call total_seconds() on the timedelta objects and replace the f-string with str.format:
ratio = (currentTime - startTime).total_seconds() / (endTime - startTime).total_seconds()
print("{:5.2%}".format(ratio))
Solution 2:[2]
It can be done using the datetime module as already mentioned in an answer, but this is a more brute-force or general approach and would work even if the time is in HH:MM:SS format
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)))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Anshumaan Mishra |
