classification
Title: Confusing error message when dividing timedelta using /
Type: behavior Stage:
Components: Interpreter Core Versions: Python 3.0
process
Status: open Resolution:
Dependencies: Superseder:
Assigned To: Nosy List: brett.cannon, haypo, skip.montanaro, webograph (4)
Priority: normal Keywords patch

Created on 2007-09-01 19:19 by skip.montanaro, last changed 2008-11-20 16:28 by webograph.

Files
File name Uploaded Description Edit Remove
py3k_datetime_1083.patch christian.heimes, 2007-11-21 10:36
Messages (3)
msg55566 - (view) Author: Skip Montanaro (skip.montanaro) Date: 2007-09-01 19:19
I discovered the hard way today that this won't work:

>>> import datetime
>>> d = datetime.timedelta(1)
>>> d / 2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for /: 'datetime.timedelta' and 'int'

The error message is misleading, because in fact timedelta
objects *do* support division by ints, just not with the
/ operator:

>>> d // 2
datetime.timedelta(0, 43200)

Is there some way the error message can be improved,
perhaps by identifying the denominator as effectively
a float?
msg55904 - (view) Author: Brett Cannon (brett.cannon) Date: 2007-09-14 00:10
If you set nb_true_div on timedelta objects to delta_divide (just like
nb_floor_div) you won't have this problem as the division will just
work.  Otherwise there is no other good way as if the divisor doesn't
work you need to return NotImplemented, which then tries the right-hand
object which fails, and 'object' returns the TypeError.  Best you could
do is a warning or something.  

But it might make sense to only set it on nb_true_div as the division
does not round anything.
msg75725 - (view) Author: STINNER Victor (haypo) Date: 2008-11-11 03:22
The current behaviour is consistent with the integer divison:
>>> 21 // 10
2
>>> timedelta(microseconds=20) // 10
datetime.timedelta(0, 0, 2)

Whereas int/int gives float:
>>> 21 / 10
2.1000000000000001
>> timedelta(microseconds=20) / 1
...
TypeError: unsupported operand type(s) for /: ...

Now in the real world, it's hard to understand that the operator // 
should be used instead of /. So timedelta()/int might be an alias to 
timedelta()//int.
History
Date User Action Args
2008-11-20 16:28:43webographsetnosy: + webograph
2008-11-11 03:22:57hayposetnosy: + haypo
messages: + msg75725
2008-01-06 22:29:45adminsetkeywords: - py3k
versions: Python 3.0
2007-11-21 10:36:56christian.heimessetkeywords: + patch
files: + py3k_datetime_1083.patch
2007-09-18 12:09:46jafosetpriority: normal
2007-09-14 00:10:16brett.cannonsetnosy: + brett.cannon
messages: + msg55904
2007-09-13 23:59:28brett.cannonsetkeywords: + py3k
versions: + Python 3.0
2007-09-01 19:19:34skip.montanarocreate