Search code examples
pythonpython-3.xtimedelta

Too many decimal places when using timedelta


I am trying to find the time in hour and minutes however, the only way I know how to do it is by using what I have done below. Below is also my output and as you can see, it the program returns seconds along with decimals after.

CODE:

def commercial_time (distance, speed_of_commercial):
    time = distance / speed_of_commercial
    seconds = time * 3600
    real = (datetime.timedelta(seconds = seconds))
    return real

OUTPUT:

9:46:04.352515

My question is, is there a way I can get rid of that ".352515"? I would also like to hide the seconds as well if that is possible.


Solution

  • Format the timedelta manually:

    def custom_format(td):
        minutes, seconds = divmod(td.seconds, 60)
        hours, minutes = divmod(minutes, 60)
        return '{:d}:{:02d}'.format(hours, minutes)
    

    Demo:

    >>> from datetime import timedelta
    >>> def custom_format(td):
    ...     minutes, seconds = divmod(td.seconds, 60)
    ...     hours, minutes = divmod(minutes, 60)
    ...     return '{:d}:{:02d}'.format(hours, minutes)
    ... 
    >>> custom_format(timedelta(hours=9, minutes=46, seconds=4, microseconds=352515))
    '9:46'
    

    This method does ignore the .days attribute. If you have timedeltas with more than 24 hours, use:

    def custom_format(td):
        minutes, seconds = divmod(td.seconds, 60)
        hours, minutes = divmod(minutes, 60)
        formatted = '{:d}:{:02d}'.format(hours, minutes)
        if td.days:
            formatted = '{} day{} {}'.format(
                td.days, 's' if td.days > 1 else '', formatted)
        return formatted
    

    Demo:

    >>> custom_format(timedelta(days=42, hours=9, minutes=46, seconds=4, microseconds=352515))
    '42 days 9:46'
    >>> custom_format(timedelta(days=1, hours=9, minutes=46, seconds=4, microseconds=352515))
    '1 day 9:46'
    >>> custom_format(timedelta(hours=9, minutes=46, seconds=4, microseconds=352515))
    '9:46'