Skip to content

Commit 5987b95

Browse files
committed
API: to_datetime, required unit with numerical (pandas-dev#15836)
* Tests * add test_to_datetime_numerical_input * add fixtures * update bool tests * Check argument * for numerical type * DataFrame with unit
1 parent 6ad32d2 commit 5987b95

File tree

3 files changed

+309
-274
lines changed

3 files changed

+309
-274
lines changed

pandas/_libs/tslib.pyx

+1-1
Original file line numberDiff line numberDiff line change
@@ -2308,7 +2308,7 @@ cpdef array_with_unit_to_datetime(ndarray values, unit, errors='coerce'):
23082308
else:
23092309

23102310
if is_raise:
2311-
raise ValueError("non convertible value {0}"
2311+
raise ValueError("non convertible value {0} "
23122312
"with the unit '{1}'".format(
23132313
val,
23142314
unit))

pandas/core/tools/datetimes.py

+19-3
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,8 @@
1414
is_float,
1515
is_list_like,
1616
is_scalar,
17-
is_numeric_dtype)
17+
is_numeric_dtype,
18+
is_bool_dtype)
1819
from pandas.core.dtypes.generic import (
1920
ABCIndexClass, ABCSeries,
2021
ABCDataFrame)
@@ -337,6 +338,7 @@ def to_datetime(arg, errors='raise', dayfirst=False, yearfirst=False,
337338
338339
"""
339340
from pandas.core.indexes.datetimes import DatetimeIndex
341+
from pandas import DataFrame
340342

341343
tz = 'utc' if utc else None
342344

@@ -446,9 +448,24 @@ def _convert_listlike(arg, box, format, name=None, tz=tz):
446448
except (ValueError, TypeError):
447449
raise e
448450

451+
def check_numerical_arg():
452+
return ((is_scalar(arg) and (is_integer(arg) or is_float(arg))) or
453+
is_numeric_dtype(np.asarray(arg)))
454+
449455
if arg is None:
450456
return None
451457

458+
if unit is not None:
459+
if isinstance(arg, (DataFrame,)):
460+
raise ValueError("unit must be None if arg is a DataFrame")
461+
if is_bool_dtype(np.asarray(arg)):
462+
raise TypeError("{0} is not convertible to datetime"
463+
.format(type(arg)))
464+
else:
465+
if (format is None and check_numerical_arg() and
466+
not isinstance(arg, (DataFrame,))):
467+
raise ValueError("a unit is required in case of numerical arg")
468+
452469
# handle origin
453470
if origin == 'julian':
454471

@@ -474,8 +491,7 @@ def _convert_listlike(arg, box, format, name=None, tz=tz):
474491

475492
# arg must be a numeric
476493
original = arg
477-
if not ((is_scalar(arg) and (is_integer(arg) or is_float(arg))) or
478-
is_numeric_dtype(np.asarray(arg))):
494+
if not check_numerical_arg():
479495
raise ValueError(
480496
"'{arg}' is not compatible with origin='{origin}'; "
481497
"it must be numeric with a unit specified ".format(

0 commit comments

Comments
 (0)