D. Tunus
D. Tunus

Reputation: 271

A way to convert numbers to seconds

I know this is not the best way to explain what I want to achieve, but I will try to do it by defining my desired output.

The context: An object passes Point A at 6:58 (format is: minute:second) and passes Point B at 7:12. Calculate the time taken to get from Point A to B.

Logically, you'd take B time away from A time to get your result. I expected: 0.14 because it takes the object 14 seconds but got 0.54 because Python by default won't know that I need it to calculate in seconds format, where the 59 is maximum before you reach a new leading number.

My code is as simple as:

A=6.58
B=7.12
print(B-A)

Upvotes: 0

Views: 94

Answers (1)

DainDwarf
DainDwarf

Reputation: 1669

Solution 1 : if you do not absolutely need float as inputs

from datetime import datetime, date, time
a = datetime.combine(date.today(), time(0, 6, 58))
b = datetime.combine(date.today(), time(0, 7, 12))

Solution 2 : if your inputs are floats

from datetime import datetime, date, time

def float_to_datetime(myfloat):
    minutes, seconds = str(myfloat).split('.')
    return datetime.combine(date.today(), time(0, int(minutes), int(seconds)))

a = float_to_datetime(6.58)
b = float_to_datetime(7.12)

In both cases, the output is:

print(b - a)
0:00:14
print((b-a).total_seconds())
14.0

Upvotes: 5

Related Questions