Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sum of datetime.datetime object gave an error TypeError: unsupported operand type(s) for +: 'datetime.datetime' and 'datetime.datetime'

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!

like image 423
mongotop Avatar asked Sep 29 '13 02:09

mongotop


1 Answers

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.

like image 173
Veedrac Avatar answered Sep 22 '22 02:09

Veedrac