Siyah Siyah - 1 year ago 54
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

has the default value string). I want to print them like this:

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:
. 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:
, but I don't know how to fix this.
didn't do the trick...

Answer Source

The easiest way is to use the datetime module.

print t
print t.strftime('%Y-%m-%d %H:%M:%S')
print t.strftime('%H:%M:%S')


1970-01-01 17:31:41.534998
1970-01-01 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))


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)


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download