-1

How in python code convert 10.5 to 10:30 (10 hours and 30 minutes).

Now time = 10.5 I need result time = 10:30

Any simple solution?

Tnx all for help

Pointer
  • 2,123
  • 3
  • 32
  • 59

3 Answers3

6

Try this:

time = 10.5

print '{0:02.0f}:{1:02.0f}'.format(*divmod(float(time) * 60, 60))

10:30

user_odoo
  • 2,284
  • 34
  • 55
2

Split the number into its integer and decimal parts, then multiply the decimal part with 60 and put them back together:

t = 10.5

hour, minute = divmod(t, 1)
minute *= 60
result = '{}:{}'.format(int(hour), int(minute))
# result: 10:30

See also the documentation for the divmod function and this question for other ways to split a float into two parts.

Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
1

You can pass the raw float value as hours to datetime.timedelta(), and then operate with it in what I think is the most comfortable way:

from datetime import datetime, timedelta

td = timedelta(hours=10.5)
dt = datetime.min + td
print("{:%H:%M}".format(dt))
print(td.total_seconds())
Yajo
  • 5,808
  • 2
  • 30
  • 34