How do I remove the microseconds from a timedelta object?

40,813

Solution 1

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

avg = sum(datetimes, datetime.timedelta(0)) / len(datetimes)
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.

Solution 2

If it is just for the display, this idea works :

avgString = str(avg).split(".")[0]

The idea is to take only what is before the point. It will return 01:23:45 for 01:23:45.1235

Solution 3

another option, given timedelta you can do:

avg = datetime.timedelta(seconds=math.ceil(avg.total_seconds()))

You can replace the math.ceil(), with math.round() or math.floor(), depending on the situation.

Solution 4

c -= timedelta(microseconds=c.microseconds)
Share:
40,813
Hobbestigrou
Author by

Hobbestigrou

Updated on September 12, 2021

Comments

  • Hobbestigrou
    Hobbestigrou over 2 years

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

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