Try Except block not working with datetime object?
<p>I have a DataFrame with some datetime data in one column and whatever else in other columns. However, some of the data is messed up, e.g.:</p>

<pre><code>11/11/2014 22:28    15.1
11/11/2014 22:29    16.1
11/11/2014 22:30    15.2
bollocks            10000
11/11/2014 22:32    15.4
:00                 
11/11/2014 22:34    15.3
</code></pre>

<p>I would like to get rid of the lines that are messed up. For now, I decided to just replace them with NaN values (but dropping them would also help, only it didn't work in the cycle so it's not an issue, in the next step I can just use <code>dropna()</code>). I'm doing this using <code>try()</code>, but the exception doesn't work. My code looks like this:</p>

<pre><code>for line in df.ix[:,"DATETIME"]:    
    try:
        line = datetime.datetime.strptime(line,"%d/%m/%Y %H:%M")
    except ValueError:
        line = 'NaN'
    except TypeError:
        line = 'NaN'
</code></pre>

<p>But in the end, I still get the <code>ValueError: time data '156004E00F455AA' does not match format '%d/%m/%Y %H:%M'</code> and the faulty lines are not replaced with <code>NaN</code>. What is wrong here? 
(I also tried putting the errors on one line like this: <code>except (ValueError, TypeError):</code> and it didn't work either...)</p>

<p>This doesn't strictly answer your query, but if you are sure that all the valid datetime strings will be of the format: <code>"%d/%m/%Y %H:%M"</code>, you can do:</p>

<pre><code>In [34]: df
Out[34]: 
           DATETIME   VALUES
0  11/11/2014 22:28     15.1
1  11/11/2014 22:29     16.1
2  11/11/2014 22:30     15.2
3          bollocks  10000.0
4  11/11/2014 22:32     15.4
5               :00      NaN
6  11/11/2014 22:34     15.3

In [35]: df = df.replace(r'^(?!\d{2}/\d{2}/\d{4} \d{2}:\d{2}).*', np.nan, regex=True)

In [36]: df
Out[36]: 
           DATETIME   VALUES
0  11/11/2014 22:28     15.1
1  11/11/2014 22:29     16.1
2  11/11/2014 22:30     15.2
3               NaN  10000.0
4  11/11/2014 22:32     15.4
5               NaN      NaN
6  11/11/2014 22:34     15.3

In [37]: df['DATETIME'].apply(lambda x: pd.to_datetime(x, format="%d/%m/%Y %H:%M"))
Out[37]: 
0   2014-11-11 22:28:00
1   2014-11-11 22:29:00
2   2014-11-11 22:30:00
3                   NaT
4   2014-11-11 22:32:00
5                   NaT
6   2014-11-11 22:34:00
Name: DATETIME, dtype: datetime64[ns]
</code></pre>

python datetime pandas