Reputation: 5
I am wondering how to find the average of the several datetimes. For example, I have the following datetime list:
a=[datetime.datetime(2010, 10, 14, 0, 14), datetime.datetime(2010, 10, 14, 0, 15), datetime.datetime(2010, 10, 14, 0, 16), datetime.datetime(2010, 10, 14, 0, 17)]
When I trying to add them up directly, it tells me that there is a
TypeError: unsupported operand type(s) for +: 'int' and 'datetime.datetime'
Not sure what is the correct way of doing this.
Very appreciated if you could help me out!
Thank you!
Upvotes: 0
Views: 136
Reputation: 25654
technically, you can calculate the "average" of your datetimes by casting their mean timestamp (UNIX time) to a new datetime object:
import datetime
l = [datetime.datetime(2010, 10, 14, 0, 14),
datetime.datetime(2010, 10, 14, 0, 15),
datetime.datetime(2010, 10, 14, 0, 16),
datetime.datetime(2010, 10, 14, 0, 17)]
middle = datetime.datetime.fromtimestamp(sum(d.timestamp() for d in l)/len(l))
# middle
# datetime.datetime(2010, 10, 14, 0, 15, 30)
Upvotes: 1