Search code examples
pythonpython-3.xdatetimetimedelta

Python 3 - How to change the syntax of a "datetime.timedelta(seconds=xxx)" object?


below a simple example using the Python interpreter:

>>> import datetime
>>> 
>>> time=datetime.timedelta(seconds=10)
>>> str(time)
'0:00:10'
>>>

how can I change the syntaxt of the time object when I convert it in a string? As reslt, I want to see '00:00:10' and not '0:00:10'. I really don't understand why the last zero in the hours block is missing, I want to see always two digits in each block. how can I do it?


Solution

  • You have to create your custom formatter to do this.

    Python3 variant of @gumption solution which is written in python2. This is the link to his solution

    Custom Formatter

    from string import Template
    
    class TimeDeltaTemp(Template):
        delimiter = "%"
    
    def strfdtime(dtime, formats):
        day = {"D": dtime.days}
        hours, rem = divmod(dtime.seconds, 3600)
        minutes, seconds = divmod(rem, 60)
        day["H"] = '{:02d}'.format(hours)
        day["M"] = '{:02d}'.format(minutes)
        day["S"] = '{:02d}'.format(seconds)
        time = TimeDeltaTemp(formats.upper())
        return time.substitute(**day)
    

    Usage

    
    import datetime
    
    time=datetime.timedelta(seconds=10)
    print(strfdtime(time, '%H:%M:%S'))
    time=datetime.timedelta(seconds=30)
    print(strfdtime(time, '%h:%m:%s'))
    
    

    Output

    00:00:10
    00:00:30