了解时间增量

编程入门 行业动态 更新时间:2024-10-28 02:31:00
本文介绍了了解时间增量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

给定下面的python代码,请帮助我理解那里发生了什么.

start_time = time.time()时间.睡眠(42)end_time = time.time()正常运行时间 = end_time - start_timehuman_uptime = str(datetime.timedelta(seconds=int(uptime)))

所以我得到了 start timeend time 之间的差异,在第 5 行,我通过强制转换对持续时间进行了四舍五入,现在呢,进一步的解释是什么?>

我知道 delta 是什么意思(平均值或差异),但是为什么我必须将 seconds = uptime 传递给 timedelta 以及为什么字符串转换效果如此之好以至于我得到 HH:MM:SS ?

解决方案

因为 timedelta 定义如下:

class datetime.timedelta([days,] [seconds,] [microseconds,] [milliseconds,] [minutes,] [hours,] [weeks])

所有参数都是可选的,默认为 0.

您可以通过这种方式轻松地说三天零四毫秒"并带有可选参数.

<预><代码>>>>datetime.timedelta(days=3, 毫秒=4)datetime.timedelta(3, 0, 4000)>>>datetime.timedelta(3, 0, 0, 4) #不需要那个.datetime.timedelta(3, 0, 4000)

对于 str 转换,它返回一个很好的格式化值而不是 __repr__ 以提高可读性.来自文档:

<块引用>

str(t) 以 [D day[s], ][H]H:MM:SS[.UUUUUU] 形式返回字符串,其中 D 对于负 t 为负.(5)

<预><代码>>>>datetime.timedelta(seconds = 42).__repr__()'datetime.timedelta(0, 42)'>>>datetime.timedelta(seconds = 42).__str__()'0:00:42'

结帐文档:

http://docs.python/library/datetime.html#时间增量对象

Given the python code below, please help me understand what is happening there.

start_time = time.time()
time.sleep(42)
end_time = time.time()

uptime = end_time - start_time

human_uptime = str(datetime.timedelta(seconds=int(uptime)))

So I get the difference between start time and end time, on line 5 I round up the duration by casting and what now, what's the further explanation?

I know what delta means(average or difference), but why do I have to pass seconds = uptime to timedelta and why does the string casting works so nicely that I get HH:MM:SS ?

解决方案

Because timedelta is defined like:

class datetime.timedelta([days,] [seconds,] [microseconds,] [milliseconds,] [minutes,] [hours,] [weeks])

All arguments are optional and default to 0.

You can easily say "Three days and four milliseconds" with optional arguments that way.

>>> datetime.timedelta(days=3, milliseconds=4)
datetime.timedelta(3, 0, 4000)
>>> datetime.timedelta(3, 0, 0, 4) #no need for that.
datetime.timedelta(3, 0, 4000)

And for str casting, it returns a nice formatted value instead of __repr__ to improve readability. From docs:

str(t) Returns a string in the form [D day[s], ][H]H:MM:SS[.UUUUUU], where D is negative for negative t. (5)

>>> datetime.timedelta(seconds = 42).__repr__()
'datetime.timedelta(0, 42)'
>>> datetime.timedelta(seconds = 42).__str__()
'0:00:42'

Checkout documentation:

http://docs.python/library/datetime.html#timedelta-objects

这篇关于了解时间增量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-04-30 11:59:57,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1393506.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:增量   时间

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!