mchangun mchangun - 1 month ago 8
Python Question

Rounding Pandas Timestamp to minutes

I want to create a

DateTimeIndex
at 1 minute intervals based on a start and end timestamp (given in microseconds since epoch) with
pd_date_range()
. To do this, I need to round the starting timestamp up and the ending timestamp down. Here is what I have so far:

import pandas as pd
start = 1406507532491431
end = 1406535228420914

start_ts = pd.to_datetime(start, unit='us') # Timestamp('2014-07-28 00:32:12.491431')
end_ts = pd.to_datetime(end, unit='us') # Timestamp('2014-07-28 08:13:48.420914')


I want to round:

start_ts
to
Timestamp('2014-07-28 00:32')
and

end_ts
to
Timestamp('2014-07-28 08:14')
.

How can I do this?

Answer

Doing this in a simple method is currently an outstanding issue here

In [22]: start = 1406507532491431

In [23]: end = 1406535228420914

[26]: dti = pd.to_datetime([start,end],unit='us')

In [27]: dti
Out[27]: 
<class 'pandas.tseries.index.DatetimeIndex'>
[2014-07-28 00:32:12.491431, 2014-07-28 08:13:48.420914]
Length: 2, Freq: None, Timezone: None

In [29]: pd.DatetimeIndex(((dti.asi8/(1e9*60)).round()*1e9*60).astype(np.int64))
Out[29]: 
<class 'pandas.tseries.index.DatetimeIndex'>
[2014-07-28 00:32:00, 2014-07-28 08:14:00]
Length: 2, Freq: None, Timezone: None

Nevertheless its quite straightforward.

Pull-requests to implement are welcome.

Comments