How do I remove the microseconds from a timedelta object?

牧云@^-^@ 提交于 2019-12-03 22:08:23
Hobbestigrou

Take the timedetla 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.

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

another option, given timedetla 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.

I found this to work for me:

start_time = datetime.now()
some_work()
end time = datetime.now()
print str(end_time - start_time)[:-3]

Output:

0:00:01.955

I thought about this after searching in https://docs.python.org/3.2/library/datetime.html#timedelta-objects

Hope this helps!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!