I'm trying to sum a list of datetime.datetime object using :
from datetime import datetime, timedelta
d= [datetime.datetime(2013, 5, 1, 9, 31, 24), datetime.datetime(2013, 6, 11, 17, 22, 18), datetime.datetime(2013, 4, 3, 16, 6, 59)]
sum_d = sum(d, timedelta())
I get the error :
TypeError: unsupported operand type(s) for +: 'datetime.datetime' and 'datetime.datetime'
any idea what am I doing wrong or how I can sum up this list?
I want to get the average of this list I was thinking about:
d_avg = sum(d, timedelta()) / len(d)
Thanks!
That's simply because you can't add times. You can add time deltas, but not times themselves.
I mean, what is 3rd Aug 1995 + 19th June 454? It doesn't make sense. You can add the distance from Year 0 but that's different to adding the dates themselves.
What do you hope to get from this calculation?
If you hope to find the mean (why?), you'll have to use a less direct route
import datetime
d = [datetime.datetime(2013, 5, 1, 9, 31, 24), datetime.datetime(2013, 6, 11, 17, 22, 18), datetime.datetime(2013, 4, 3, 16, 6, 59)]
d[0] + sum((d_i-d[0] for d_i in d), datetime.timedelta(0)) / len(d)
#>>> datetime.datetime(2013, 5, 5, 22, 20, 13, 666667)
This finds the sum of offsets from d[0]
, means those and then adds that offset back on.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With