python - How to strictly limit float to two numbers to get hh:mm:ss? -
i newbie in python tries learn it, things vague me right now. hope has time point me in right direction.
what trying do? asking 3 inputs convert float (because i've been told raw_input
has default value string). want print them this: hh:mm:ss
i this, 3 times:
time_to_think = float(raw_input("enter time needed: "))
after that, have if-statement checks if input bigger 50.
that works well, until need print them...
so have this:
if time_to_think > 50 time_to_think_sec = round(time_to_think / 1000) # gives me time 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 output strictly: hh:mm:ss
. gives me lot of decimals, while want rounded numbers 2 numbers. if time_to_think_sec = 1241414
, want 12
it has with: %.2f:%.2f:%.2f
, don't know how fix this. %02f:%02f:%02f
didn't trick...
the easiest way use 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 use fromtimestamp
instead of utcfromtimestamp
, can unexpected answer hours because messes time zones. full timestamp has years , stuff in there, can ignore , deal in hours. otherwise, have subtract off epoch.
if want manually, think want cast hours , minutes int
after rounding , use format code %02d
. can leave seconds float , use %02.xf
if want or 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
Comments
Post a Comment