Skip to content

BUG: fix to_datetime to handle int16 and int8 #13464

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions doc/source/whatsnew/v0.18.2.txt
Original file line number Diff line number Diff line change
Expand Up @@ -517,3 +517,5 @@ Bug Fixes


- Bug in ``Categorical.remove_unused_categories()`` changes ``.codes`` dtype to platform int (:issue:`13261`)

- Bug in ``DataFrame.to_datetime()`` raises ValueError in case of dtype ``int8`` and ``int16`` (:issue:`13451`)
27 changes: 27 additions & 0 deletions pandas/tseries/tests/test_timeseries.py
Original file line number Diff line number Diff line change
Expand Up @@ -2563,6 +2563,33 @@ def test_dataframe(self):
with self.assertRaises(ValueError):
to_datetime(df2)

def test_dataframe_dtypes(self):
# #13451
df = DataFrame({'year': [2015, 2016],
'month': [2, 3],
'day': [4, 5]})

# int16
result = to_datetime(df.astype('int16'))
expected = Series([Timestamp('20150204 00:00:00'),
Timestamp('20160305 00:00:00')])
assert_series_equal(result, expected)

# mixed dtypes
df['month'] = df['month'].astype('int8')
df['day'] = df['day'].astype('int8')
result = to_datetime(df)
expected = Series([Timestamp('20150204 00:00:00'),
Timestamp('20160305 00:00:00')])
assert_series_equal(result, expected)

# float
df = DataFrame({'year': [2000, 2001],
'month': [1.5, 1],
'day': [1, 1]})
with self.assertRaises(ValueError):
to_datetime(df)


class TestDatetimeIndex(tm.TestCase):
_multiprocess_can_split_ = True
Expand Down
6 changes: 5 additions & 1 deletion pandas/tseries/tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -508,7 +508,11 @@ def f(value):

def coerce(values):
# we allow coercion to if errors allows
return to_numeric(values, errors=errors)
values = to_numeric(values, errors=errors)
# prevent overflow in case of int8 or int16
if com.is_integer_dtype(values):
values = values.astype('int64', copy=False)
return values

values = (coerce(arg[unit_rev['year']]) * 10000 +
coerce(arg[unit_rev['month']]) * 100 +
Expand Down