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, ..., 201
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:
np.round(dtindex_or_datetime_col.astype(np.int64), -9).astype('datetime64[ns]')
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:
from pandas.lib import Timestamp
t1 = Timestamp('2012-1-1 00:00:00')
t2 = Timestamp('2012-1-1 00:00:00.000333')
In [4]: t1
Out[4]:
In [5]: t2
Out[5]:
In [6]: t2.microsecond
Out[6]: 333
In [7]: t1.value
Out[7]: 1325376000000000000L
In [8]: t2.value
Out[8]: 1325376000000333000L
# Alternatively: t2.value - t2.value % 1000000000
In [9]: long(round(t2.value, -9)) # round milli-, micro- and nano-seconds
Out[9]: 1325376000000000000L
In [10]: Timestamp(long(round(t2.value, -9)))
Out[10]:
Hence you can apply this to the entire index:
def to_the_second(ts):
return Timestamp(long(round(ts.value, -9)))
dtindex.map(to_the_second)