使用python查找以秒为单位的时间差作为整数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3638532/
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
find time difference in seconds as an integer with python
提问by Richard
I need to find the time difference in seconds with python. I know I can get the difference like this:
我需要用python找到以秒为单位的时差。我知道我可以得到这样的区别:
from datetime import datetime
now = datetime.now()
....
....
....
later = datetime.now()
difference = later-now
how do I get difference in total seconds?
我如何获得总秒数的差异?
采纳答案by Michael Mior
import time
now = time.time()
...
later = time.time()
difference = int(later - now)
回答by rkhayrov
If all you need is to measure a time span, you may use time.time()function which returns seconds since Epoch as a floating point number.
如果您只需要测量时间跨度,您可以使用time.time()函数返回自 Epoch 以来的秒数作为浮点数。
回答by Robert Longson
The total_seconds method will return the difference, including any fractional part.
total_seconds 方法将返回差值,包括任何小数部分。
from datetime import datetime
now = datetime.now()
...
later = datetime.now()
difference = (later - now).total_seconds()
You can convert that to an integer via int() if you want
如果需要,您可以通过 int() 将其转换为整数
回答by Jiaconda
Adding up the terms of the timedelta tuple with adequate multipliers should give you your answer. diff.days*24*60*60 + difference.seconds
将 timedelta 元组的项与足够的乘数相加应该会给你答案。 diff.days*24*60*60 + difference.seconds
from datetime import datetime
now = datetime.now()
...
later = datetime.now()
diff = later-now
diff_in_seconds = diff.days*24*60*60 + diff.seconds
The variable 'diff' is a timedelta object that is a tuple of (days, seconds, microseconds) as explained in detail here https://docs.python.org/2.4/lib/datetime-timedelta.html. All other units (hours, minutes..) are converted into this format.
变量 'diff' 是一个 timedelta 对象,它是一个(天、秒、微秒)元组,详细解释如下https://docs.python.org/2.4/lib/datetime-timedelta.html。所有其他单位(小时、分钟……)都转换为这种格式。
>> diff = later- now
>> diff
datetime.timedelta(0, 8526, 689000)
>> diff_in_seconds = diff.days*24*60*60 + diff.seconds
>> diff_in_seconds
>> 8527
Another way to look at it would be if instead of later-now (therefore a positive time difference), you instead have a negative time difference (earlier-now), where the time elapsed between the two is still the same as in the earlier example
另一种看待它的方法是,如果不是现在(因此是正时差),而是负时差(更早现在),两者之间经过的时间仍然与之前相同例子
>> diff = earlier-now
>> diff
datetime.timedelta(-1, 77873, 311000)
>> diff_in_seconds = diff.days*24*60*60 + diff.seconds
>> diff_in_seconds
>> -8527
Hence, even if we are sure the duration is less than 1 day, it is necessary to take the day term into account, since it is an important term in case of negative time difference.
因此,即使我们确定持续时间小于 1 天,也有必要考虑日项,因为它是负时差情况下的重要项。

