How do I get a datetime object out of a YYYY-Q string?
<p>The <a href="https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior" rel="nofollow">datetime.strptime</a> reference does not provide an option for the YYYY-Qx (with x = {1,...,4}) date format. Do I need the <a href="http://dateutil.readthedocs.io/en/stable/parser.html" rel="nofollow">dateutil.parser</a> for that?</p>

<p>For my implementation, I chose the 15th of the second month as the representative date. That means, if this function receives "2016-Q3" as date, it will be resolved to "2016-08-15".</p>

<pre><code>def df_quarter(self, date):
    ypart = datetime.datetime.strptime(date.split('-')[0], '%Y')
    qpart = re.sub('Q', '', date.split('-')[1])
    qmid = 2+3*(int(qpart)-1)
    if qmid &lt; 10:
        qmid = "0" + str(qmid)
    date = str(ypart.year) + '-' + qmid + '-15'
</code></pre>

<p>You could simply hard-code the relationship between quarters and dates, and use <code>re.sub</code> to replace <code>Q(\d)</code> with the appropriate value:</p>

<pre><code>import re
def df_quarter(date):
    q = {'1':'02-15', '2':'05-15', '3':'08-15', '4':'11-15'}
    return re.sub('Q(\d)', lambda match, q=q: q[match.group(1)], date)
</code></pre>

<hr>

<pre><code>In [36]: df_quarter('2016-Q1')
Out[36]: '2016-02-15'

In [35]: df_quarter('2016-Q2')
Out[35]: '2016-05-15'

In [34]: df_quarter('2016-Q3')
Out[34]: '2016-08-15'

In [37]: df_quarter('2016-Q4')
Out[37]: '2016-11-15'
</code></pre>

<hr>

<p>Or, if you want <code>df_quarter</code> to return a <code>datetime.datetime</code> object:</p>

<pre><code>import re
import datetime as DT
def df_quarter(date):
    q = {'1':'02-15', '2':'05-15', '3':'08-15', '4':'11-15'}
    date = re.sub('Q(\d)', lambda match, q=q: q[match.group(1)], date)
    return DT.datetime.strptime(date, '%Y-%m-%d')
</code></pre>

<hr>

<p>If you would rather compute the month based on a formula, you could instead use</p>

<pre><code>def df_quarter(date):
    date = re.sub('Q(\d)', lambda match: '{:02d}-15'.format(int(match.group(1))*3-1), date)
    return DT.datetime.strptime(date, '%Y-%m-%d')
</code></pre>

<p>Notice that the format specifier <code>02d</code> replaces the integer, <code>int(match.group(1))*3-1</code> with a 2-digit string padded with a zero on the left if necessary.</p>

python date datetime