0

I'm doing a calculation that returns the total number of seconds. Then I turn that into days, hours, minutes, seconds using python time.strftime()

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

But, using %-j begins on 001, so my calculation is always off by 1 day. Is there a way to start %-j on 000? Is there a better way to do this? Thanks!

m0nhawk
  • 22,980
  • 9
  • 45
  • 73
h.and.h
  • 690
  • 1
  • 8
  • 26

1 Answers1

4

This seems like an extremely convoluted way to get days, hours, minutes and seconds from a total seconds value. You can just use division:

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))

To handle the pluralisation of these (001 day instead of 001 days), you can modify the helper function to do it.

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))

If you handle plurals often, see Plural String Formatting for the geneal case.

Community
  • 1
  • 1
Artyer
  • 31,034
  • 3
  • 47
  • 75
  • 1
    What about leap seconds? – Marichyasana Apr 06 '17 at 15:54
  • How would you format the {:03} days to say just 'day' if there's only 1? – h.and.h Apr 06 '17 at 15:56
  • @Marichyasana These are SI seconds. – Artyer Apr 06 '17 at 16:18
  • Python documentation: The following directives can be embedded in the format string. They are shown without the optional field width and precision specification, and are replaced by the indicated characters in the strftime() result: The range really is 0 to 61; this accounts for leap seconds and the (very rare) double leap seconds. – Marichyasana Apr 07 '17 at 21:19
  • @Marichyasana That probably wasn't the intended result in this situation, and it would have been leap seconds since the Unix Epoch, which is probably not what was intended. – Artyer Apr 08 '17 at 13:32