這似乎是一個非常複雜的方式來從總秒數值中獲得日,小時,分鐘和秒。你可以只用除法:
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的情況下,駐港。
閏秒呢? – Marichyasana
如果只有1天,你會如何格式化{:03}天來表示只有'天'? –
@Marichyasana這些是SI秒。 – Artyer