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>You can use a regex with a capture group around the four digits, while also making sure you have a particular pattern around it. I would probably look for something that:</p>

<ul>
<li><p>4 digits and a capture <code>(\d{4})</code></p></li>
<li><p>hyphen <code>-</code></p></li>
<li><p>two digits <code>\d{2}</code></p></li>
<li><p>hyphen <code>-</code></p></li>
<li><p>two digits <code>\d{2}</code></p></li>
</ul>

<p>Giving: <code>(\d{4})-\d{2}-\d{2}</code></p>

<p>Demo:</p>

<pre><code>&gt;&gt;&gt; import re
&gt;&gt;&gt; d = re.findall('(\d{4})-\d{2}-\d{2}', 'years since 1250-01-01 0:0:0')
&gt;&gt;&gt; d
['1250']
&gt;&gt;&gt; d[0]
'1250'
</code></pre>

<p>if you need it as an int, just cast it as such:</p>

<pre><code>&gt;&gt;&gt; int(d[0])
1250
</code></pre>

python regex