Python 如何从 timedelta 对象中删除微秒?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18470627/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 10:50:16  来源:igfitidea点击:

How do I remove the microseconds from a timedelta object?

pythondatetimeformattimedelta

提问by Hobbestigrou

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)

采纳答案by Hobbestigrou

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

取 timedelta 并删除它自己的微秒,作为微秒和只读属性:

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.

我还没有找到更好的解决方案。

回答by sangorys

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:45for 01:23:45.1235

这个想法是只取点之前的东西。它将返回01:23:4501:23:45.1235

回答by eran

another option, given timedelta you can do:

另一种选择,给定 timedelta 你可以这样做:

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.

您可以根据情况将math.ceil()、替换为math.round()math.floor()

回答by Eitan.k.

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

我在https://docs.python.org/3.2/library/datetime.html#timedelta-objects 中搜索后想到了这个

Hope this helps!

希望这可以帮助!

回答by ldav1s

Given that timedeltaonly stores days, seconds and microseconds internally, you can construct a new timedelta without microseconds:

鉴于timedelta仅在内部存储天、秒和微秒,您可以构建一个没有微秒的新 timedelta:

from datetime import timedelta
datetimes = (timedelta(hours=1, minutes=5, seconds=30, microseconds=9999), 
             timedelta(minutes=35, seconds=17, microseconds=55), 
             timedelta(hours=2, minutes=17, seconds=3, microseconds=1234))
avg = sum(datetimes, timedelta(0)) / len(datetimes) # timedelta(0, 4756, 670429)
avg = timedelta(days=avg.days, seconds=avg.seconds) # timedelta(0, 4756)