Skip to content

Commit

Permalink
Ensure that DatetimeArray keeps reference to original data (pandas-de…
Browse files Browse the repository at this point in the history
  • Loading branch information
TomAugspurger authored and Pingviinituutti committed Feb 28, 2019
1 parent 46044a2 commit 3a6c6d6
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 1 deletion.
5 changes: 4 additions & 1 deletion pandas/_libs/tslibs/conversion.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -99,10 +99,13 @@ def ensure_datetime64ns(arr: ndarray, copy: bool=True):

ivalues = arr.view(np.int64).ravel()

result = np.empty(shape, dtype='M8[ns]')
result = np.empty(shape, dtype=NS_DTYPE)
iresult = result.ravel().view(np.int64)

if len(iresult) == 0:
result = arr.view(NS_DTYPE)
if copy:
result = result.copy()
return result

unit = get_datetime64_unit(arr.flat[0])
Expand Down
9 changes: 9 additions & 0 deletions pandas/tests/arrays/test_datetimelike.py
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,15 @@ def test_array_i8_dtype(self, tz_naive_fixture):
assert result.base is expected.base
assert result.base is not None

def test_from_array_keeps_base(self):
# Ensure that DatetimeArray._data.base isn't lost.
arr = np.array(['2000-01-01', '2000-01-02'], dtype='M8[ns]')
dta = DatetimeArray(arr)

assert dta._data is arr
dta = DatetimeArray(arr[:0])
assert dta._data.base is arr

def test_from_dti(self, tz_naive_fixture):
tz = tz_naive_fixture
dti = pd.date_range('2016-01-01', periods=3, tz=tz)
Expand Down
12 changes: 12 additions & 0 deletions pandas/tests/tslibs/test_conversion.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,3 +57,15 @@ def test_tz_convert_corner(self, arr):
timezones.maybe_get_tz('US/Eastern'),
timezones.maybe_get_tz('Asia/Tokyo'))
tm.assert_numpy_array_equal(result, arr)


class TestEnsureDatetime64NS(object):
@pytest.mark.parametrize('copy', [True, False])
@pytest.mark.parametrize('dtype', ['M8[ns]', 'M8[s]'])
def test_length_zero_copy(self, dtype, copy):
arr = np.array([], dtype=dtype)
result = conversion.ensure_datetime64ns(arr, copy=copy)
if copy:
assert result.base is None
else:
assert result.base is arr

0 comments on commit 3a6c6d6

Please sign in to comment.