Search code examples
pythonpython-2.7strftime

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


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!


Solution

  • 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.