convert time to float in python

To convert time to a floating point number representing seconds, you can use the total_seconds() method of a timedelta object or the time() function of the time module. Here are two examples:

main.py
import datetime

# convert a timedelta object to float seconds
td = datetime.timedelta(hours=1, minutes=30, seconds=45)
seconds = td.total_seconds()
print(seconds)  # 5445.0

# convert a time object to float seconds
t = datetime.time(hour=1, minute=30, second=45)
seconds = t.hour * 3600 + t.minute * 60 + t.second + t.microsecond / 1000000
print(seconds)  # 5445.0
366 chars
12 lines

In the first example, we create a timedelta object representing 1 hour, 30 minutes, and 45 seconds. We then call its total_seconds() method to get the total number of seconds as a float.

In the second example, we create a time object representing 1 hour, 30 minutes, and 45 seconds. We then calculate the total number of seconds as the sum of the hours, minutes, seconds, and fractional seconds (microseconds divided by 1 million).

gistlibby LogSnag