Convert a string with ns precision to datetime in a panda dataframe
<p>I'm having a hard time converting a string with ns precision in a datetime format in a panda dataframe.</p>

<p>I have a data frame like the following :</p>

<pre><code>print df
     Event     Time
0    A         08:00:00.123456789
1    B         08:00:00.234567890
2    C         08:00:00.345678901
</code></pre>

<p>I would like to convert the Time column from string to datetime without losing the ns precision.
I tried following :</p>

<pre><code>df['Time'] = pd.to_datetime(df['Time'])
</code></pre>

<p>but when I print the <code>df</code> I see that I only have up to <code>us</code> precision.</p>

<p><code>df['Time'] = df['Time'].astype('datetime64[ns]')</code> </p>

<p>but here I get an error like </p>

<blockquote>
  <p>"Error parsing datetime string "08:00:00.345678901" at position 2"</p>
</blockquote>

<p>The following did the trick for me:</p>

<pre><code>&gt;&gt;&gt; df['Time'] = pd.to_datetime(df['Time'], format='%H:%M:%S.%f')
&gt;&gt;&gt; df
  Event                          Time
0     A 1900-01-01 08:00:00.123456789
1     B 1900-01-01 08:00:00.234567890
2     C 1900-01-01 08:00:00.345678901
</code></pre>

<p>As noted in the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html" rel="nofollow">documentation for <code>pd.to_datetime</code></a> concerning the <code>format</code> argument:</p>

<blockquote>
  <p>strftime to parse time, eg â%d/%m/%Yâ, <strong>note that â%fâ will parse all the way up to nanoseconds</strong>.</p>
</blockquote>

python pandas