Skip to content

Commit df26cd4

Browse files
committed
BUG: pd.Timedelta np.int, np.float. fixes pandas-dev#8757
1 parent b3df1ff commit df26cd4

File tree

2 files changed

+20
-3
lines changed

2 files changed

+20
-3
lines changed

pandas/tseries/tests/test_timedeltas.py

+4
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,10 @@ def test_construction(self):
3838
self.assertEqual(Timedelta(10.0,unit='d').value, expected)
3939
self.assertEqual(Timedelta('10 days').value, expected)
4040
self.assertEqual(Timedelta(days=10).value, expected)
41+
self.assertEqual(Timedelta(days=10.0).value, expected)
42+
43+
for npdtype in [np.int64, np.int32, np.int16, np.float64, np.float32, np.float16]:
44+
self.assertEqual(Timedelta(days=npdtype(10)).value, expected)
4145

4246
expected += np.timedelta64(10,'s').astype('m8[ns]').view('i8')
4347
self.assertEqual(Timedelta('10 days 00:00:10').value, expected)

pandas/tslib.pyx

+16-3
Original file line numberDiff line numberDiff line change
@@ -1619,6 +1619,7 @@ class Timedelta(_Timedelta):
16191619
Denote the unit of the input, if input is an integer. Default 'ns'.
16201620
days, seconds, microseconds, milliseconds, minutes, hours, weeks : numeric, optional
16211621
Values for construction in compat with datetime.timedelta.
1622+
np ints and floats will be coereced to python ints and floats.
16221623
16231624
Notes
16241625
-----
@@ -1632,11 +1633,23 @@ class Timedelta(_Timedelta):
16321633
if value is None:
16331634
if not len(kwargs):
16341635
raise ValueError("cannot construct a TimeDelta without a value/unit or descriptive keywords (days,seconds....)")
1636+
# sanitize timedelta input.
1637+
# needed to avoid np to python-native int/float typecasting issues
1638+
for argname, argvalue in kwargs.items():
1639+
if isinstance(argvalue, (int, float)):
1640+
continue
1641+
elif np.issubdtype(argvalue, int):
1642+
kwargs[argname] = int(argvalue)
1643+
elif np.issubdtype(argvalue, float):
1644+
kwargs[argname] = float(argvalue)
16351645
try:
16361646
value = timedelta(**kwargs)
1637-
except (TypeError):
1638-
raise ValueError("cannot construct a TimeDelta from the passed arguments, allowed keywords are "
1639-
"[days, seconds, microseconds, milliseconds, minutes, hours, weeks]")
1647+
except TypeError as e:
1648+
if 'unsupported type' in str(e):
1649+
raise e
1650+
else:
1651+
raise ValueError("cannot construct a TimeDelta from the passed arguments, allowed keywords are "
1652+
"[days, seconds, microseconds, milliseconds, minutes, hours, weeks]")
16401653

16411654
if isinstance(value, Timedelta):
16421655
value = value.value

0 commit comments

Comments
 (0)