Timestamp
对于更一般的舍入,您可以利用 Pandas对象主要使用标准库datetime.datetime
API的事实,包括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