より一般的な丸めには、Pandasオブジェクトがメソッドを含む標準ライブラリ API をTimestamp
ほとんど使用しているという事実を利用できます。datetime.datetime
datetime.datetime.replace()
したがって、マイクロ秒の丸めの問題を解決するには、次のようにします。
import datetime
import pandas as pd
times = pd.date_range('2012-1-1 02:03:04.499',periods=3,freq='1ms')
# Add 5e5 microseconds and truncate to simulate rounding
times_rounded = [(x + datetime.timedelta(microseconds=5e5)).replace(microsecond=0) for x in times]
from IPython.display import display
print('Before:')
display(list(times))
print('After:')
display(list(times_rounded))
出力:
Before:
[Timestamp('2012-01-01 02:03:04.499000', offset='L'),
Timestamp('2012-01-01 02:03:04.500000', offset='L'),
Timestamp('2012-01-01 02:03:04.501000', offset='L')]
After:
[Timestamp('2012-01-01 02:03:04', offset='L'),
Timestamp('2012-01-01 02:03:05', offset='L'),
Timestamp('2012-01-01 02:03:05', offset='L')]
たとえば、同じ手法を使用して、最も近い日に丸めることができます (うるう秒などを気にしない限り)。
times = pd.date_range('2012-1-1 08:00:00', periods=3, freq='4H')
times_rounded = [(x + datetime.timedelta(hours=12)).replace(hour=0, second=0, microsecond=0) for x in times]
この SO 投稿に触発されました: https://stackoverflow.com/a/19718411/1410871