Skip to content

Commit e323274

Browse files
committed
BUG: allow conversion of Timestamp and Timedelta to string in astype (GH 9757)
1 parent a004c59 commit e323274

File tree

3 files changed

+16
-6
lines changed

3 files changed

+16
-6
lines changed

doc/source/whatsnew/v0.16.1.txt

+1
Original file line numberDiff line numberDiff line change
@@ -66,3 +66,4 @@ Bug Fixes
6666

6767

6868
- Bug in ``Series.quantile`` on empty Series of type ``Datetime`` or ``Timedelta`` (:issue:`9675`)
69+
- Bug causing ``astype(str)`` to fail for dtype ``datetime64`` or ``timedelta64`` (:issue:`9757`)

pandas/core/common.py

+6-6
Original file line numberDiff line numberDiff line change
@@ -2636,7 +2636,12 @@ def _astype_nansafe(arr, dtype, copy=True):
26362636
if not isinstance(dtype, np.dtype):
26372637
dtype = _coerce_to_dtype(dtype)
26382638

2639-
if is_datetime64_dtype(arr):
2639+
if issubclass(dtype.type, compat.text_type):
2640+
# in Py3 that's str, in Py2 that's unicode
2641+
return lib.astype_unicode(arr.ravel()).reshape(arr.shape)
2642+
elif issubclass(dtype.type, compat.string_types):
2643+
return lib.astype_str(arr.ravel()).reshape(arr.shape)
2644+
elif is_datetime64_dtype(arr):
26402645
if dtype == object:
26412646
return tslib.ints_to_pydatetime(arr.view(np.int64))
26422647
elif dtype == np.int64:
@@ -2674,11 +2679,6 @@ def _astype_nansafe(arr, dtype, copy=True):
26742679
elif arr.dtype == np.object_ and np.issubdtype(dtype.type, np.integer):
26752680
# work around NumPy brokenness, #1987
26762681
return lib.astype_intsafe(arr.ravel(), dtype).reshape(arr.shape)
2677-
elif issubclass(dtype.type, compat.text_type):
2678-
# in Py3 that's str, in Py2 that's unicode
2679-
return lib.astype_unicode(arr.ravel()).reshape(arr.shape)
2680-
elif issubclass(dtype.type, compat.string_types):
2681-
return lib.astype_str(arr.ravel()).reshape(arr.shape)
26822682

26832683
if copy:
26842684
return arr.astype(dtype)

pandas/tests/test_series.py

+9
Original file line numberDiff line numberDiff line change
@@ -5433,6 +5433,15 @@ def test_astype_str(self):
54335433
expec = s.map(compat.text_type)
54345434
assert_series_equal(res, expec)
54355435

5436+
# GH9757
5437+
ts = Series([Timestamp('2010-01-04 00:00:00')])
5438+
ts = ts.astype(str)
5439+
self.assertEqual(ts.dtype, np.object_)
5440+
5441+
td = Series([Timedelta(1, unit='d')])
5442+
td = td.astype(str)
5443+
self.assertEqual(td.dtype, np.object_)
5444+
54365445
def test_astype_unicode(self):
54375446

54385447
# GH7758

0 commit comments

Comments
 (0)