Skip to content

round function added to DatetimeIndex #8942

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 2 commits 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
22 changes: 22 additions & 0 deletions pandas/tests/test_index.py
Original file line number Diff line number Diff line change
Expand Up @@ -1886,6 +1886,28 @@ def test_reindex_preserves_tz_if_target_is_empty_list_or_array(self):
self.assertEqual(str(index.reindex([])[0].tz), 'US/Eastern')
self.assertEqual(str(index.reindex(np.array([]))[0].tz), 'US/Eastern')

def test_round(self):
index = pd.DatetimeIndex([ pd.Timestamp('20120827 12:05:00.002'),
pd.Timestamp('20130101 12:05:01'),
pd.Timestamp('20130712 15:10:00'),
pd.Timestamp('20130712 15:10:00.000004') ])

result = index.round('1s')

tm.assert_index_equal(result, pd.DatetimeIndex([
pd.Timestamp('20120827 12:05:00'),
pd.Timestamp('20130101 12:05:01'),
pd.Timestamp('20130712 15:10:00'),
pd.Timestamp('20130712 15:10:00') ]) )

result = index.round('1h')

tm.assert_index_equal(result, pd.DatetimeIndex([
pd.Timestamp('20120827 12:00:00'),
pd.Timestamp('20130101 12:00:00'),
pd.Timestamp('20130712 15:00:00'),
pd.Timestamp('20130712 15:00:00') ]) )


class TestPeriodIndex(Base, tm.TestCase):
_holder = PeriodIndex
Expand Down
5 changes: 5 additions & 0 deletions pandas/tseries/index.py
Original file line number Diff line number Diff line change
Expand Up @@ -592,6 +592,11 @@ def _is_dates_only(self):
from pandas.core.format import _is_dates_only
return _is_dates_only(self.values)

def round(self, freq):
if isinstance(freq, compat.string_types):
freq = to_offset(freq).nanos
return DatetimeIndex(((self.asi8/freq).round()*freq).astype(np.int64))

@property
def _formatter_func(self):
from pandas.core.format import _get_format_datetime64
Expand Down