2016-11-10 97 views
1

我是一个试图学习Python的新手,但现在有些事情对我来说太模糊了。我希望有人有时间把我指向正确的方向。如何严格限制float为两个数字来获得hh:mm:ss?

我想要做什么?我在询问某人的三个输入,我将它们全部转换为浮点数(因为我已被告知raw_input具有默认值字符串)。我想打印出来像这样:hh:mm:ss

我是这样做的,三次:

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

在那之后,我有一个if语句谁检查,如果输入的是大于50

这一切运作良好,直到我需要打印出来......

所以我有这样的:

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

而现在,总算:

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

我所要的输出是严格:hh:mm:ss。但是这给了我很多小数,而我只想用两个数字来舍入数字。所以,如果time_to_think_sec = 1241414,我希望它是

它做的东西:%.2f:%.2f:%.2f,但我不知道如何解决这个问题。 %02f:%02f:%02f没有伎俩...

+0

它看起来。浮点数明确指出带点值的数字。同样以你的格式,你要求它打印2位小数。 – Ajurna

回答

1

最简单的方法是使用日期时间模块。

t=datetime.datetime.utcfromtimestamp(63101534.9981/1000) 
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 
17:31:41 

如果使用fromtimestamp而不是utcfromtimestamp,你可以得到的时间意想不到的答案,因为它与时区食堂。完整的时间戳有几年和东西在里面,但你可以忽略它,只需几个小时即可完成。否则,你必须减去时代。

如果您想手动执行此操作,我认为您要在舍入后将小时数和分钟数转换为int,并使用格式代码%02d。你可以离开秒钟float和使用%02.xf如果你想或做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) 

结果:像你应该使用INT的

17:31:41.535 
17:31:42 
+0

所以,像这样:'time_to_think_sec = int(round(time_to_think/1000))'或者什么? – Siyah

+1

感谢队友,投票表决并标记为正确答案。干杯! – Siyah

相关问题