Skip to content

Commit fd3912d

Browse files
evanpwEvan Wright
authored and
Evan Wright
committed
ENH: Allow conversion of datetime64 and timedelta64 to string in astype (GH 9757)
1 parent a4ae0cf commit fd3912d

File tree

3 files changed

+18
-6
lines changed

3 files changed

+18
-6
lines changed

doc/source/whatsnew/v0.16.1.txt

+1
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ Enhancements
3030
df = DataFrame(np.random.randn(3, 3), columns=['A', 'B', 'C'])
3131
df.drop(['A', 'X'], axis=1, errors='ignore')
3232

33+
- Allow conversion of values with dtype ``datetime64`` or ``timedelta64`` to strings using ``astype(str)`` (:issue:`9757`)
3334

3435
.. _whatsnew_0161.api:
3536

pandas/core/common.py

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

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

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

pandas/tests/test_series.py

+11
Original file line numberDiff line numberDiff line change
@@ -5511,6 +5511,17 @@ def test_astype_str(self):
55115511
expec = s.map(compat.text_type)
55125512
assert_series_equal(res, expec)
55135513

5514+
# GH9757
5515+
ts = Series([Timestamp('2010-01-04 00:00:00')])
5516+
s = ts.astype(str)
5517+
expected = Series([str(ts.values[0])])
5518+
assert_series_equal(s, expected)
5519+
5520+
td = Series([Timedelta(1, unit='d')])
5521+
s = td.astype(str)
5522+
expected = Series([str(td.values[0])])
5523+
assert_series_equal(s, expected)
5524+
55145525
def test_astype_unicode(self):
55155526

55165527
# GH7758

0 commit comments

Comments
 (0)