Extracting year from string in python
<p>How can I parse the foll. in python to extract the year:</p>

<pre><code>'years since 1250-01-01 0:0:0'
</code></pre>

<p>The answer should be 1250</p>

<p>There are all sorts of ways to do it, here are several options:</p>

<ul>
<li><p><a href="https://pypi.python.org/pypi/python-dateutil" rel="nofollow"><code>dateutil</code> parser</a> in a "fuzzy" mode:</p>

<pre><code>In [1]: s = 'years since 1250-01-01 0:0:0'

In [2]: from dateutil.parser import parse

In [3]: parse(s, fuzzy=True).year  # resulting year would be an integer
Out[3]: 1250
</code></pre></li>
<li><p>regular expressions with a <em>capturing group</em>:</p>

<pre><code>In [2]: import re

In [3]: re.search(r"years since (\d{4})", s).group(1)
Out[3]: '1250'
</code></pre></li>
<li><p>splitting by "since" and then by a dash:</p>

<pre><code>In [2]: s.split("since", 1)[1].split("-", 1)[0].strip()
Out[2]: '1250'
</code></pre></li>
<li><p>or may be even splitting by the first dash and slicing the first substring:</p>

<pre><code>In [2]: s.split("-", 1)[0][-4:]
Out[2]: '1250'
</code></pre></li>
</ul>

<p>The last two involve more "moving parts" and might not be applicable depending on possible variations of the input string.</p>

python regex