I have two lap time strings I need to subtract, the format is minutes, seconds, milliseconds
. This is to compare a new world record time to the previous holder's time. The result will always be positive.
Example input:
x = "1:09.201"
y = "0:57.199"
# 12.002
I have two working solutions, but I'm not sure I'm content. Am I able to make this better, shorter, cleaner, or more readable?
1st solution:
from datetime import datetime, time, timedelta
def getTimeDifference(t1, t2):
wrTime = convertTimeString(t1)
wrTime = datetime(2000, 1, 1,
minute=wrTime["minutes"],
second=wrTime["seconds"],
microsecond=wrTime["milliseconds"]*1000
)
previousWrTime = convertTimeString(t2)
previousWrTime = datetime(2000, 1, 1,
minute=previousWrTime["minutes"],
second=previousWrTime["seconds"],
microsecond=previousWrTime["milliseconds"]*1000
)
current, prev = wrTime.timestamp(), previousWrTime.timestamp()
difference = round(prev - current, 3)
return difference
def convertTimeString(time):
time = time.replace(":", " ").replace(".", " ").split()
try:
converted = {
"minutes": int(time[0]),
"seconds": int(time[1]),
"milliseconds": int(time[2])
}
except IndexError:
print("Index error occured when formatting time from scraped data")
return converted
x = "1:09.201"
y = "0:57.199"
print(getTimeDifference(y, x))
2nd solution:
from datetime import datetime, time, timedelta
# Takes two m:ss.fff time strings
# Example: 1:
def getTimeDifference(t1, t2):
wrTime = convertTimeString(t1)
time1 = timedelta(
minutes=wrTime["minutes"],
seconds=wrTime["seconds"],
milliseconds=wrTime["milliseconds"])
previousWrTime = convertTimeString(t2)
time2 = timedelta(
minutes=previousWrTime["minutes"],
seconds=previousWrTime["seconds"],
milliseconds=previousWrTime["milliseconds"])
diff = time2 - time1
formatted = f"{diff.seconds}.{int(diff.microseconds/1000):>03}"
return formatted # 0.000 seconds
def convertTimeString(time):
time = time.replace(":", " ").replace(".", " ").split()
try:
converted = {
"minutes": int(time[0]),
"seconds": int(time[1]),
"milliseconds": int(time[2])
}
except IndexError:
print("Index error occured when formatting time from scraped data")
return converted
x = "1:09.201"
y = "0:57.199"
print(getTimeDifference(y, x))
```