2017-04-06 75 views
0

我正在做一個返回總秒數的計算。然後,我把它轉換成天,小時,分鐘,使用python time.strftime秒()如何在Python 2.7中使用time.strftime()開始一天的工作?

total_time = time.strftime("%-j days, %-H hours, %-M minutes, %-S seconds,", time.gmtime(total_seconds)) 

但是,使用%-j在001開始,所以我的計算是始終關閉1天。有沒有辦法在000上啓動%-j?有一個更好的方法嗎?謝謝!

回答

4

這似乎是一個非常複雜的方式來從總秒數值中獲得日,小時,分鐘和秒。你可以只用除法:

def secs_to_days(seconds): 
    minutes, seconds = divmod(seconds, 60) 
    hours, minutes = divmod(minutes, 60) 
    days, hours = divmod(hours, 24) 
    return (days, hours, minutes, seconds) 

total_time = ("{:03} days, {:02} hours, {:02} minutes, " 
       "{:02} seconds,").format(*secs_to_days(total_seconds)) 

爲了處理這些的名字的複數(001天而不是001天),您可以修改輔助函數來做到這一點。

def secs_to_days(seconds): 
    minutes, seconds = divmod(seconds, 60) 
    hours, minutes = divmod(minutes, 60) 
    days, hours = divmod(hours, 24) 

    seconds = "{:02} second{}".format(seconds, "" if seconds == 1 else "s") 
    minutes = "{:02} minute{}".format(minutes, "" if minutes == 1 else "s") 
    hours = "{:02} hour{}".format(hours, "" if hours == 1 else "s") 
    days = "{:03} day{}".format(days, "" if days == 1 else "s") 

    return (days, hours, minutes, seconds) 

total_time = ", ".join(secs_to_days(seconds)) 

如果你經常處理複數,看到Plural String Formatting的情況下,駐港。

+1

閏秒呢? – Marichyasana

+0

如果只有1天,你會如何格式化{:03}天來表示只有'天'? –

+0

@Marichyasana這些是SI秒。 – Artyer