Python: How to filter a DataFrame of dates in Pandas by a particular date within a window of some days?
<p>I have a DataFrame of dates and would like to filter for a particular date +- some days.</p>

<pre><code>import pandas as pd
import numpy as np
import datetime

dates = pd.date_range(start="08/01/2009",end="08/01/2012",freq="D")
df = pd.DataFrame(np.random.rand(len(dates), 1)*1500, index=dates, columns=['Power'])
</code></pre>

<p>If I select lets say date <code>2009-08-03</code> and a window of <code>5</code> days, output would be similar to:</p>

<pre><code>&gt;&gt;&gt; 
                  Power
2010-07-29   713.108020
2010-07-30  1055.109543
2010-07-31   951.159099
2010-08-01  1350.638983
2010-08-02   453.166697
2010-08-03  1066.859386
2010-08-04  1381.900717
2010-08-05   107.489179
2010-08-06  1195.945723
2010-08-07  1209.762910
2010-08-08   349.554492
</code></pre>

<p>N.B.: The original problem I am trying to accomplish is under <a href="http://stackoverflow.com/questions/40117702/python-filter-dataframe-in-pandas-by-hour-day-and-month-grouped-by-year">Python: Filter DataFrame in Pandas by hour, day and month grouped by year</a></p>

<p>The function I created to accomplish this is <code>filterDaysWindow</code> and can be used as follows:</p>

<pre><code>import pandas as pd
import numpy as np
import datetime

dates = pd.date_range(start="08/01/2009",end="08/01/2012",freq="D")
df = pd.DataFrame(np.random.rand(len(dates), 1)*1500, index=dates, columns=['Power'])

def filterDaysWindow(df, date, daysWindow):
    """
    Filter a Dataframe by a date within a window of days

    @type df: DataFrame
    @param df: DataFrame of dates

    @type date: datetime.date
    @param date: date to focus on

    @type daysWindow: int
    @param daysWindow: Number of days to perform the days window selection

    @rtype: DataFrame
    @return: Returns a DataFrame with dates within date+-daysWindow
    """    
    dateStart = date - datetime.timedelta(days=daysWindow)
    dateEnd = date + datetime.timedelta(days=daysWindow)
    return df [dateStart:dateEnd]

df_filtered = filterDaysWindow(df, datetime.date(2010,8,3), 5)
print df_filtered
</code></pre>

python date datetime pandas dataframe