I have a pandas.DatetimeIndex
, e.g.:
pd.date_range('2012-1-1 02:03:04.000',periods=3,freq='1ms')
>>> [2012-01-01 02:03:04, ..., 2012-01-01 02:03:04.002000]
I would like to round the dates (Timestamp
s) to the nearest second. How do I do that? The expected result is similar to:
[2012-01-01 02:03:04.000000, ..., 2012-01-01 02:03:04.000000]
Is it possible to accomplish this by rounding a Numpy datetime64[ns]
to seconds without changing the dtype
[ns]
?
np.array(['2012-01-02 00:00:00.001'],dtype='datetime64[ns]')
round()
method was added for DatetimeIndex, Timestamp, TimedeltaIndex and Timedelta in pandas 0.18.0. Now we can do the following:round()
accepts frequency parameter. String aliases for it are listed here.There is little point in changing the index itself - since you can just generate using
date_range
with the desired frequency parameter as in your question.I assume what you are trying to do is change the frequency of a Time Series that contains data, in which case you can use
resample
(documentation). For example if you have the following time series:Then you can change the frequency to seconds using resample, specifying how you want to aggregate the values (mean, sum etc.):
For more general rounding, you can make use of the fact that Pandas
Timestamp
objects mostly use the standard librarydatetime.datetime
API, including thedatetime.datetime.replace()
method.So, to solve your microsecond rounding problem, you could do:
Output:
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):
Inspired by this SO post: https://stackoverflow.com/a/19718411/1410871
Update: if you're doing this to a DatetimeIndex / datetime64 column a better way is to use
np.round
directly rather than via an apply/map:Old answer (with some more explanation):
Whilst @Matti's answer is clearly the correct way to deal with your situation, I thought I would add an answer how you might round a Timestamp to the nearest second:
Hence you can apply this to the entire index: