diff --git a/doc/source/v0.15.0.txt b/doc/source/v0.15.0.txt index 96d9b7c58c41a..3a3eac835f7e2 100644 --- a/doc/source/v0.15.0.txt +++ b/doc/source/v0.15.0.txt @@ -770,3 +770,8 @@ Bug Fixes needed interpolating (:issue:`7173`). - Bug where ``col_space`` was ignored in ``DataFrame.to_string()`` when ``header=False`` (:issue:`8230`). +- Bug with ``DatetimeIndex.asof`` incorrectly matching partial strings and +returning the wrong date (:issue:`8245`). + + + diff --git a/pandas/core/index.py b/pandas/core/index.py index 61fb3bffc55a4..961e488026731 100644 --- a/pandas/core/index.py +++ b/pandas/core/index.py @@ -1052,6 +1052,9 @@ def asof(self, label): if isinstance(label, (Index, ABCSeries, np.ndarray)): raise TypeError('%s' % type(label)) + if not isinstance(label, Timestamp): + label = Timestamp(label) + if label not in self: loc = self.searchsorted(label, side='left') if loc > 0: @@ -1059,8 +1062,6 @@ def asof(self, label): else: return np.nan - if not isinstance(label, Timestamp): - label = Timestamp(label) return label def asof_locs(self, where, mask): diff --git a/pandas/tests/test_index.py b/pandas/tests/test_index.py index 97149e8f224d3..8d0b54f2ef0b4 100644 --- a/pandas/tests/test_index.py +++ b/pandas/tests/test_index.py @@ -390,6 +390,12 @@ def test_asof(self): d = self.dateIndex[0].to_datetime() tm.assert_isinstance(self.dateIndex.asof(d), Timestamp) + def test_asof_datetime_partial(self): + idx = pd.date_range('2010-01-01', periods=2, freq='m') + expected = Timestamp('2010-01-31') + result = idx.asof('2010-02') + self.assertEqual(result, expected) + def test_nanosecond_index_access(self): s = Series([Timestamp('20130101')]).values.view('i8')[0] r = DatetimeIndex([s + 50 + i for i in range(100)])