问题描述
限时送ChatGPT账号..给定下面的python代码,请帮助我理解那里发生了什么.
start_time = time.time()时间.睡眠(42)end_time = time.time()正常运行时间 = end_time - start_timehuman_uptime = str(datetime.timedelta(seconds=int(uptime)))
所以我得到了 start time
和 end 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:关键词]
发布评论