title: Pandas - filter data that are in last n month using query
body: <p>I want to filter my data frame based on <code>time</code> column using <strong>query</strong> function and get rows with <code>time</code> in last <code>N</code> month(or any time periods).</p>
  
  <p>Basically I need something like:</p>
  
  <pre><code>df = df.query("time.isin(timeperiod('5M'))")
  
  </code></pre>
  
  <p>or</p>
  
  <pre><code>df = df.query("now() &gt;= time &gt;= now() - timeperiod('5M')")
  </code></pre>
  
  <p>I'm trying to create query patterns for my filter functions and It's important to use 
  <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.query.html" rel="nofollow noreferrer">query()</a> function.</p>
  
  <p>Note that <code>timeperiod()</code> and <code>now()</code> functions are not available and I used them for better understanding of the solution I want.I mean please define these functions in your solution.</p>
  
  <p>Sample:</p>
  
  <pre><code>df = pd.DataFrame()
  df['time1'] = pd.date_range('1/1/2019', periods=1000, freq='D')
  df['time2'] = pd.date_range('1/1/2018', periods=1000, freq='D')
  </code></pre>
  
  <p>Sample data can have some other columns.</p>
  
  <p>I need to filter data to get records within last <code>N</code> month for each of given columns using <code>query()</code> function. For example I want records with <code>time1</code> in last 2 months and <code>time2</code> in last 3 months. Like getting records of people who were hired during last 3 month and were let go during last 2 months.</p>
  
  <p><strong>UPDATE 1:</strong></p>
  
  <p>thanks to <a href="https://chat.stackoverflow.com/users/2901002">@jezrael</a> I could get <code>now()</code> function in <code>query()</code> like this:</p>
  
  <pre><code>df = df.query("@pd.Timestamp('now') &gt;= time")
  </code></pre>
  
  <p>of course <code>Timestamp</code> could be replaced by 'to_datetime` or something else.</p>
  
  <p>But the problem is when I try to get a timestamp for the start of period like this:</p>
  
  <pre><code>df = df.query("time &gt;= (@pd.Timestamp('now') + @pd.to_timedelta('30day'))")
  </code></pre>
  
  <p>I get:
  <code>Cannot convert input ... of type &lt;class 'pandas._libs.tslibs.timedeltas.Timedelta'&gt; to Timestamp</code></p>
  
  <p>Again using DateOffset or other time-delta functions result with the similar error.</p>
  
  <p>But using <strong>variables</strong> to set target date (as <a href="https://chat.stackoverflow.com/users/2901002">@jezrael</a> mentioned) works.</p>
  
  <p>I will use <strong>variables</strong> as I don't see any other way right now but I will keep this Question open to see if there is any better way.</p>