How to round a Pandas `DatetimeIndex`?

前端 未结 4 1319
栀梦
栀梦 2021-01-11 10:04

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         


        
4条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-11 10:42

    round() method was added for DatetimeIndex, Timestamp, TimedeltaIndex and Timedelta in pandas 0.18.0. Now we can do the following:

    In[114]: index = pd.DatetimeIndex([pd.Timestamp('2012-01-01 02:03:04.000'), pd.Timestamp('2012-01-01 02:03:04.002'), pd.Timestamp('20130712 02:03:04.500'), pd.Timestamp('2012-01-01 02:03:04.501')])
    
    In[115]: index.values
    Out[115]: 
    array(['2012-01-01T02:03:04.000000000', '2012-01-01T02:03:04.002000000',
           '2013-07-12T02:03:04.500000000', '2012-01-01T02:03:04.501000000'], dtype='datetime64[ns]')
    
    In[116]: index.round('S')
    Out[116]: 
    DatetimeIndex(['2012-01-01 02:03:04', '2012-01-01 02:03:04',
                   '2013-07-12 02:03:04', '2012-01-01 02:03:05'],
                  dtype='datetime64[ns]', freq=None)
    

    round() accepts frequency parameter. String aliases for it are listed here.

提交回复
热议问题