Define a pandas.tseries.index.DatetimeIndex using 2 datetimes (dt_start and dt_stop) and a timedelta

StackOverflow https://stackoverflow.com/questions/21643407

سؤال

With Pandas we can define a pandas.tseries.index.DatetimeIndex using the following syntax:

rng = pd.date_range(dt_start, dt_stop, freq='5Min')

freq is a string.

I would like to define the same kind of DatetimeIndex using a timedelta as freq

td = datetime.timedelta(minutes=5)
rng = pd.date_range(dt_start, dt_stop, freq=td)

I did some uggly hack such as

rng = pd.date_range(dt_start, dt_stop, freq="%sMin" % int(td.total_seconds()/60))

but I wonder if there is not a better way to do this.

هل كانت مفيدة؟

المحلول

A more robust way to get this is to use a DateOffset (which you can pass as freq to date_range).

Since microseconds is the smallest unit for a timedelta:

In [11]: td = datetime.timedelta(minutes=5, microseconds=100)

In [12]: pd.offsets.Micro(td.total_seconds() * 10 ** 6)
Out[12]: <300000100 * Micros>

Note: I think it's a good enhancement request for this function to accept a timedelta object...

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top