Skip to content

Commit

Permalink
Raise TypeError for any non-parseable argument in to_datetime (rapids…
Browse files Browse the repository at this point in the history
…ai#14044)

Avoids the following incorrect behavior

```python
In [7]: cudf.to_datetime([True])
Out[7]: GenericIndex([True], dtype='bool')

In [1]: import pandas

In [2]: pandas.to_datetime([True])
TypeError: <class 'bool'> is not convertible to datetime
```

Authors:
  - Matthew Roeschke (https://github.com/mroeschke)

Approvers:
  - Bradley Dice (https://github.com/bdice)

URL: rapidsai#14044
  • Loading branch information
mroeschke authored Sep 7, 2023
1 parent e81d79e commit 0190c29
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 8 deletions.
16 changes: 8 additions & 8 deletions python/cudf/cudf/core/tools/datetimes.py
Original file line number Diff line number Diff line change
Expand Up @@ -294,12 +294,8 @@ def to_datetime(
def _process_col(col, unit, dayfirst, infer_datetime_format, format):
if col.dtype.kind == "M":
return col
elif col.dtype.kind == "m":
raise TypeError(
f"dtype {col.dtype} cannot be converted to {_unit_dtype_map[unit]}"
)

if col.dtype.kind in ("f"):
elif col.dtype.kind in ("f"):
if unit not in (None, "ns"):
factor = cudf.Scalar(
column.datetime._unit_to_nanoseconds_conversion[unit]
Expand All @@ -325,8 +321,9 @@ def _process_col(col, unit, dayfirst, infer_datetime_format, format):
)
else:
col = col.as_datetime_column(dtype="datetime64[ns]")
return col

if col.dtype.kind in ("i"):
elif col.dtype.kind in ("i"):
if unit in ("D", "h", "m"):
factor = cudf.Scalar(
column.datetime._unit_to_nanoseconds_conversion[unit]
Expand All @@ -340,6 +337,7 @@ def _process_col(col, unit, dayfirst, infer_datetime_format, format):
)
else:
col = col.as_datetime_column(dtype=_unit_dtype_map[unit])
return col

elif col.dtype.kind in ("O"):
if unit not in (None, "ns") or col.null_count == len(col):
Expand All @@ -364,11 +362,13 @@ def _process_col(col, unit, dayfirst, infer_datetime_format, format):
format = column.datetime.infer_format(
element=col.element_indexing(0)
)
col = col.as_datetime_column(
return col.as_datetime_column(
dtype=_unit_dtype_map[unit],
format=format,
)
return col
raise TypeError(
f"dtype {col.dtype} cannot be converted to {_unit_dtype_map[unit]}"
)


def get_units(value):
Expand Down
6 changes: 6 additions & 0 deletions python/cudf/cudf/tests/test_datetime.py
Original file line number Diff line number Diff line change
Expand Up @@ -2156,3 +2156,9 @@ def test_format_timezone_not_implemented(code):
cudf.to_datetime(
["2020-01-01 00:00:00 UTC"], format=f"%Y-%m-%d %H:%M:%S %{code}"
)


@pytest.mark.parametrize("arg", [True, False])
def test_args_not_datetime_typerror(arg):
with pytest.raises(TypeError):
cudf.to_datetime([arg])

0 comments on commit 0190c29

Please sign in to comment.