简体   繁体   中英

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!

That's simply because you can't add times. You can add time deltas , but not times themselves.

I mean, what is 3 rd Aug 1995 + 19 th 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 ;-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM