如何在 python 2.7 中使用 time.strftime() 从 000 开始一天?

How do I begin day at 000 using time.strftime() in python 2.7?

我正在计算 returns 总秒数。然后我使用 python time.strftime()

将其转换为天、小时、分钟、秒
total_time = time.strftime("%-j days, %-H hours, %-M minutes, %-S seconds,", time.gmtime(total_seconds))

但是,使用 %-j 从 001 开始,所以我的计算总是偏差 1 天。有没有办法在 000 上启动 %-j?有一个更好的方法吗?谢谢!

这似乎是一种从总秒值中获取天、小时、分钟和秒的极其复杂的方法。你可以只使用除法:

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 了解一般情况。