2016-11-10 24 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

相關問題