title: Count on a rolling time window in pandas
body: <p>I'm trying to return a count on a time window about a (moving) fixed point.</p>
  
  <p>It's an attempt to understand the condition of an instrument at any time, as a function of usage prior to it.</p>
  
  <p>So if the instrument is used at 12.05pm, 12.10, 12.15, 12.30, 12.40 and 1pm, the usage counts would be:</p>
  
  <p>12.05 -> 1 (once in the last hour)</p>
  
  <p>12.10 -> 2</p>
  
  <p>12.15 -> 3</p>
  
  <p>12.30 -> 4</p>
  
  <p>12.40 -> 5</p>
  
  <p>1.00  -> 6</p>
  
  <p>... but then lets say usage resumes at 1.06:
  1.06 -> 6
  this doesn't increase the count, as the first run is over an hour ago.</p>
  
  <p><strong>How can I calculate this count and append it as a column?</strong></p>
  
  <p>It feels like this is an groupby/aggregate/count using possibly timedeltas in a lambda function, but I don't know where to start past that.</p>
  
  <p>I'd like to be able to play with the time window too, so not just the past hour, but the hour surrounding an instance i.e. + and -30 minutes.</p>
  
  <p>The following code gives a starting dataframe:</p>
  
  <pre><code>s = pd.Series(pd.date_range('2020-1-1', periods=8000, freq='250s'))
  df = pd.DataFrame({'Run time': s})
  df_sample = df.sample(6000)
  df_sample = df_sample.sort_index()
  </code></pre>
  
  <p>The best help i found (and to be fair i can usually hack together from the logic) was this <a href="https://stackoverflow.com/questions/48483033/distinct-count-on-a-rolling-time-window">Distinct count on a rolling time window</a> but i've not managed this time.</p>
  
  <p>Thanks</p>