homepage

This issue tracker has been migrated to GitHub , and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: call sum on list of timedelta throws TypeError
Type: behavior Stage: resolved
Components: Library (Lib) Versions: Python 3.6, Python 3.2, Python 3.3, Python 3.4, Python 3.5, Python 2.7
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: abarry, kevinjqiu, r.david.murray, sedrubal
Priority: normal Keywords:

Created on 2015年11月04日 04:11 by kevinjqiu, last changed 2022年04月11日 14:58 by admin. This issue is now closed.

Files
File name Uploaded Description Edit
demo.py kevinjqiu, 2015年11月04日 04:11
Messages (4)
msg254038 - (view) Author: Kevin Jing Qiu (kevinjqiu) * Date: 2015年11月04日 04:11
Calling sum() on a list of timedelta objects results in TypeError: unsupported operand type(s) for +: 'int' and 'datetime.timedelta'
Here's a script that illustrates this behaviour: (also attached)
import datetime
x = [datetime.timedelta(1), datetime.timedelta(2)]
print(x[0] + x[1]) # datetime.timedelta(3)
print(sum(x)) # TypeError: unsupported operand type(s) for +: 'int' and 'datetime.timedelta'
The bug is present in all version of Python 2 and Python 3
msg254039 - (view) Author: Anilyka Barry (abarry) * (Python triager) Date: 2015年11月04日 04:34
`sum` has an optional `start` parameter, which defaults to 0, and is used as the first item to add. Since timedeltas and ints are not interoperable, that means you have to explicitly tell sum what to use.
The following code works:
>>> e=[datetime.timedelta(3), datetime.timedelta(5)]
>>> sum(e, datetime.timedelta(0))
datetime.timedelta(8)
This is not a bug, but maybe this could use a more descriptive error message? I don't know.
msg254057 - (view) Author: R. David Murray (r.david.murray) * (Python committer) Date: 2015年11月04日 15:22
I don't think this warrants a special error message. If you get it, it is obvious you weren't yourself adding an int to a timedelta, so the next logical course of action should be to look at the docs for sum.
msg398214 - (view) Author: (sedrubal) Date: 2021年07月26日 07:07
What is the reason for this start parameter? Why will sum not just use the first entry of the input sequence?
I think at least a error message that points programmers into the right direction was very helpful.
History
Date User Action Args
2022年04月11日 14:58:23adminsetgithub: 69735
2021年07月26日 07:07:03sedrubalsetnosy: + sedrubal
messages: + msg398214
2015年11月04日 15:22:31r.david.murraysetstatus: open -> closed

nosy: + r.david.murray
messages: + msg254057

resolution: not a bug
stage: resolved
2015年11月04日 04:34:27abarrysetnosy: + abarry
messages: + msg254039
2015年11月04日 04:11:46kevinjqiucreate

AltStyle によって変換されたページ (->オリジナル) /