For more general rounding, you can make use of the fact that Pandas Timestamp
objects mostly use the standard library datetime.datetime
API, including the datetime.datetime.replace()
method.
So, to solve your microsecond rounding problem, you could do:
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))
Output:
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')]
You can use the same technique to, e.g., round to the nearest day (as long as you're not concerned about leap seconds and the like):
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]
Inspired by this SO post: https://mcmap.net/q/791972/-round-timestamp-to-nearest-day-in-python
date_range
defaults to day frequency, I assume you meant to havepd.date_range('2012-1-1 00:00.000',periods=2, freq='S')
– Wuhan