Siyah Siyah - 3 months ago 15
Python Question

How to strictly limit float to two numbers to get hh:mm:ss?

I am newbie in Python. I am trying to learn it, but some things are just too vague for me right now. I hope someone has the time to point me in the right direction.

What am I trying to do? I am asking three inputs from someone which I all convert to a float (because I've been told the

raw_input
has the default value string). I want to print them like this:
hh:mm:ss


I do that like this, three times:

time_to_think = float(raw_input("Enter the time you needed: "))


After that, I have an if-statement who checks if the input is bigger than 50.

That all works well, until I need to print them...

So I have this:

if time_to_think > 50
time_to_think_sec = round(time_to_think / 1000) # this gives me the time to think in seconds


And now, finally:

print "The time needed: %.2f:%.2f:%.2f" % (time_to_think_sec, time_to_think_minutes, time_to_think_hours)


I want the output to be strictly:
hh:mm:ss
. But this gives me a lot of decimals, while I just want rounded numbers with just two numbers. So if
time_to_think_sec = 1241414
, I want it to be 12

It has to do something with:
%.2f:%.2f:%.2f
, but I don't know how to fix this.
%02f:%02f:%02f
didn't do the trick...

Answer Source

The easiest way is to use the datetime module.

t=datetime.datetime.utcfromtimestamp(63101534.9981/1000)
print t
print t.strftime('%Y-%m-%d %H:%M:%S')
print t.strftime('%H:%M:%S')

Result

1970-01-01 17:31:41.534998
1970-01-01 17:31:41
17:31:41

If you use fromtimestamp instead of utcfromtimestamp, you can get an unexpected answer for the hours because it messes with time zones. The full timestamp has years and stuff in there, but you can ignore that and just deal in hours. Otherwise, you have to subtract off the epoch.

If you want to do this manually, I think you want to cast hours and minutes as int after rounding and use format code %02d. You can leave seconds as float and use %02.xf if you want or do int(round(time_to_think_seconds))

time_to_think_ms=63101534.9981
time_to_think_hours=int(floor(time_to_think_ms/1000./60./60.))
time_to_think_minutes=int(floor(time_to_think_ms-time_to_think_hours*60*60*1000)/1000./60.)
time_to_think_seconds=(time_to_think_ms-time_to_think_hours*1000*60*60-time_to_think_minutes*60*1000)/1000
time_to_think_seconds_2=int(round((time_to_think_ms-time_to_think_hours*1000*60*60-time_to_think_minutes*60*1000)/1000))

print '%02d:%02d:%02.3f'%(time_to_think_hours,time_to_think_minutes,time_to_think_seconds)
print '%02d:%02d:%02d'%(time_to_think_hours,time_to_think_minutes,time_to_think_seconds_2)

Result:

17:31:41.535
17:31:42