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

StackOverflow https://stackoverflow.com/questions/19073821

سؤال

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.

نصائح أخرى

You cannot sum this list: as the error message said, datetime.datetime objects cannot be added. What on Earth, for example, would you expect datetime.datetime(2013, 5, 1, 9, 31, 24), datetime.datetime(2013, 6, 11, 17, 22, 18) to return? Python generally won't do things that make no sense at all ;-)

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top