Reputation: 1
Im trying to convert a decimal time number such as 23.456, 0.5555, 1.9999 etc. to seconds (as a whole number).
I have made a function that converts the decimal time to hours and minutes. For example, converting to hours:
def decimal_to_hours(t)
return math.floor(t)
And then for decimal time to minutes:
def decimal_to_mins(t)
if t < 1:
return math.floor(t * 60)
if t % 1 == 0:
return 0
elif t > 1:
return math.floor((t - math.floor(t)) * 60)
So my problem is I don't know how I would convert the fraction to seconds. Any help would be apreciated.
Upvotes: 0
Views: 4866
Reputation: 60207
Just convert to seconds and do the original operation: floored modulo.
from math import floor
time_hours = 23.99431
time_minutes = time_hours * 60
time_seconds = time_minutes * 60
hours_part = floor(time_hours)
minutes_part = floor(time_minutes % 60)
seconds_part = floor(time_seconds % 60)
print("{h}:{m}:{s}".format(h=hours_part, m=minutes_part, s=seconds_part))
#>>> 23:59:39
Upvotes: 3
Reputation: 1630
def convert_decimal_to_time(decimal):
values_in_seconds = [('days', 60*60*24), ('hours', 60*60), ('minutes', 60), ('seconds', 1)]
output_dict = {}
num_seconds = int(decimal * 3600)
for unit, worth in values_in_seconds:
output_dict[unit] = num_seconds // worth
num_seconds = num_seconds % worth
return output_dict
convert_decimal_to_time(23.99431)
# {'minutes': 59, 'hours': 23, 'days': 0, 'seconds': 39}
convert_decimal_to_time(2.75)
# {'minutes': 45, 'seconds': 0, 'hours': 2, 'days': 0}
convert_decimal_to_time(252.5)
# {'minutes': 30, 'seconds': 0, 'hours': 12, 'days': 10}
Upvotes: 2