0

Best way to convert a string (like 1:00, 3:45) to a float? I'm planning on use this (see below) code to calculate the time for a runner's 2 and 3 mile times but I need to first convert a string into an int or float to be able to use it in these calculations.

twoMileTimes=[]
threeMileTimes=[]
for i in range(len(runnerNames)):
    twoMileTimes.append(round(twoMileMark[i]-oneMileMark[i],2))
    threeMileTime = fiveKMark[i]*(3/3.1)
    threeMileTime -= twoMileMark[i]
    threeMileTimes.append(round(threeMileTime,2))
  • 4
    If the input is `3:45`, what should the result be? By what logic? – Karl Knechtel Sep 22 '20 at 01:31
  • 2
    so 45 seconds is 75% of a minute so `3:45` should become `3.75` although I did just realize that you can divide the seconds by 60, cause I guess I wasn't thinking. – DartRuffian Sep 22 '20 at 01:37
  • Does this answer your question? [Converting time to a float](https://stackoverflow.com/questions/47043841/converting-time-to-a-float) – Gino Mempin Sep 22 '20 at 02:50
  • 1
    @GinoMempin I ended finding a solution already (just dividing `seconds` by 60 but have now run into another error with my code which I can't seem to figure out. (In the now edited post) – DartRuffian Sep 22 '20 at 03:06
  • If you have a **NEW** question, then ask a **NEW** question. **Do not edit or revise the original** because that would invalidate the comments and the existing answer/s (which still refer to the original question of converting time to float). – Gino Mempin Sep 22 '20 at 03:26
  • 1
    Got it, making a new question right now. Can be found here: https://stackoverflow.com/questions/64002703/using-exec-to-define-a-variable-raises-an-nameerror-when-referencing-it – DartRuffian Sep 22 '20 at 03:29

1 Answers1

1
>>> s = "3:45"
>>> a, b = map(int, s.split(":"))
>>> a
3
>>> b
45
>>> b = b / 60
>>> b
0.75
>>> res = round(a + b, 2)
>>> res
3.75
>>>
Etoneja
  • 1,023
  • 1
  • 8
  • 15