Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Average of two timestamps in python

I have two timestamps (pandas.tslib.Timestamp) ts1 and ts2 and I want to calculate the average of them.

(ts1+ts2)/2

However, I am getting this error:

TypeError: unsupported operand type(s) for +: 'Timestamp' and 'Timestamp'

Thank you for any help.

like image 542
Karel Macek Avatar asked Jan 18 '17 15:01

Karel Macek


2 Answers

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
like image 160
Haleemur Ali Avatar answered Sep 18 '22 01:09

Haleemur Ali


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.

How ? This way:

average_delta = (ts2 - ts1) / 2
average_ts = ts1 + average_delta
like image 27
Saksow Avatar answered Sep 19 '22 01:09

Saksow