Datetime comparison within Pandas messing with datetime.time()
<p>I have a large excel file with start and finish times for marathon runners. In order to determine the number of runners still on the course after delayed start times, I've tried to import the data into Pandas and use the built in pandas comparison in order to return a list of runners running at a certain time. At a given time x, runners on the course would have a start time &lt;= x and a endtime > x. However in Pandas one of these is giving me an error. </p>

<p>I've imported the dataframe from Excel using the <code>read_exel</code> which automatically converts the start times and end times as <code>Datetime.time</code> objects. Here's some sample data</p>

<pre><code>df = pd.DataFrame(
{'name':['Bob','Sue','Joe'],
 'start_time':[datetime.time(6,50,0),datetime.tââime(6,55,0),datetiââme.time(7,0,0)], 
 'start_time':[datetime.time(7,15,04),datetime.time(7,21,41)ââ,datetime.time(7,23,24)],})
</code></pre>

<p>Runners start at <code>6:50</code> and I would like to make a list of the amount of runners on the course every <code>4</code> minutes. So I've set up some variables to handle that:</p>

<pre><code>race_start = datetime.datetime(100,1,1,6,50)
intervaul = datetime.timedelta(minutes = 4)
capture_time = race_start
</code></pre>

<p>Then I try to select the correct rows using Pandas built in selection</p>

<pre><code>df[df.start_time &lt;= capture_time.time() &amp; df.end_time &gt; capture_time.time()]
</code></pre>

<p>However I get the error: </p>

<blockquote>
  <p>TypeError: Cannot compare datetime.time and unicode</p>
</blockquote>

<p>In fact, <code>df.start_time &lt;= capture_time.time()</code> is perfectly fine and runs, but <code>df.end_time &lt;= capture_time.time()</code> returns this error.</p>

<p>I have no idea what is going on here and any help would be appreciated.</p>

<p>You need add <code>()</code> twice only, first can be omit, but by best practices are used too:</p>

<pre><code>pd[(pd.start_time &lt;= capture_time.time()) &amp; (pd.end_time &lt;= capture_time.time())]
</code></pre>

<p>Or maybe <code>dtype</code> of column <code>end_time</code> is not <code>datetime</code>, so you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html" rel="nofollow"><code>to_datetime</code></a>:</p>

<pre><code>pd.end_time = pandas.to_datetime(pd.end_time)
</code></pre>

<p>I think name for <code>DataFrame</code> is better <code>df</code>, then you can use:</p>

<pre><code>import pandas as pd

df.end_time = pd.to_datetime(df.end_time)
</code></pre>

python datetime pandas indexing time