pandas python中两个时间戳的平均值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41723105/
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
Average of two timestamps in python
提问by Karel Macek
I have two timestamps (pandas.tslib.Timestamp) ts1
and ts2
and I want to calculate the average of them.
我有两个时间戳 (pandas.tslib.Timestamp) ts1
,ts2
我想计算它们的平均值。
(ts1+ts2)/2
However, I am getting this error:
但是,我收到此错误:
TypeError: unsupported operand type(s) for +: 'Timestamp' and 'Timestamp'
Thank you for any help.
感谢您的任何帮助。
回答by Haleemur Ali
subtracting a timestamp from another generates an interval, which may then be divided.
从另一个中减去一个时间戳会生成一个间隔,然后可以将其分开。
as the error says, adding timestamps is not allowed.
正如错误所说,不允许添加时间戳。
the solution involves calculating the interval, halving the interval and then adding the halved interval to the earlier timestamp or subtracting from the later timestamp.
该解决方案涉及计算间隔,将间隔减半,然后将减半的间隔添加到较早的时间戳或从较晚的时间戳中减去。
from pandas.tslib import Timestamp
d1 = Timestamp.now()
# wait a few seconds
d2 = Timestamp.now()
d3 = d1 + (d2 - d1) / 2
# d3 will be the timestamp exactly in between d1 & d2
回答by Saksow
Objects similar to datetime.datetime
objects do not support addition as well, because there is no meaning in adding dates. You should use datetime.timedelta
to get the average time.
类似于datetime.datetime
对象的对象也不支持加法,因为加法没有意义。您应该使用datetime.timedelta
来获取平均时间。
How ? This way:
如何 ?这边走:
average_delta = (ts2 - ts1) / 2
average_ts = ts1 + average_delta
回答by Boud
This is how I take the median of 2 timestamps:
这就是我如何取 2 个时间戳的中位数:
ts1 = pd.Timestamp('2016-1-18 10:00')
ts2 = pd.Timestamp('2016-1-18 10:20')
ts1+(ts2-ts1)/2
Out[11]: Timestamp('2016-01-18 10:10:00')
No need to test if ts2 is greater than ts2 as the equation is symmetrical.
由于方程是对称的,因此无需测试 ts2 是否大于 ts2。
回答by student
This method gave the same result as others:
这种方法给出了与其他方法相同的结果:
t1 = Timestamp('2017-01-18 10:00:00.0000000')
t2 = Timestamp('2017-01-20 10:00:00.0000000')
average = Timestamp((t1.value + t2.value)/2.0)