pythondatetimeformattimedelta

Remove the microseconds from a timedelta object


I do a calculation of average time, and I would like to display the resulted average without microseconds.

avg = sum(timedeltas, datetime.timedelta(0)) / len(timedeltas)

Solution

  • Take the timedelta and remove its own microseconds, as microseconds and read-only attribute:

    avg = sum(timedeltas, datetime.timedelta(0)) / len(timedeltas)
    avg = avg - datetime.timedelta(microseconds=avg.microseconds)
    

    You can make your own little function if it is a recurring need:

    import datetime
    
    def chop_microseconds(delta):
        return delta - datetime.timedelta(microseconds=delta.microseconds)
    

    I have not found a better solution.