title: How to dynamically access an attribute of an object in Python?
body: <p>I have a data that looks like this</p>
  
  <pre><code>data = [(u'Del', datetime.datetime(2019, 11, 1, 0, 0), 59L), (u'Bom', datetime.datetime(2019, 11, 1, 0, 0), 449L), (u'Del', datetime.datetime(2019, 12, 1, 0, 0), 0L), (u'Bom', datetime.datetime(2019, 12, 1, 0, 0), 45L)]
  </code></pre>
  
  <p>I am using <code>pandas</code> to do some data wrangling. Now I need to get a list of dates from the data in certain formats like <code>hour</code>, <code>month</code>, <code>year</code> etc. So to extract dates from the data in <code>month</code>, this is what I do</p>
  
  <pre><code>import pandas as pd
  import datetime
  
  df = pd.DataFrame(data)
  dates = df[1].dt.month.values.tolist()
  </code></pre>
  
  <p>So I get a list of months. But in the method <code>df[1].dt.year.values.tolist()</code>, I want to assign the granularity dynamically ie it could either be <code>dt.month</code> or <code>dt.year</code> based on the variable value.</p>
  
  <p>Say I have a variable called <code>granularity_val</code></p>
  
  <p>So if <code>granularity_val = 'year'</code>, I should do</p>
  
  <pre><code>dates = df[1].dt.year.values.tolist()
  </code></pre>
  
  <p>Similarly if <code>granularity_val = 'month'</code>, I should do</p>
  
  <pre><code>dates = df[1].dt.month.values.tolist()
  </code></pre>
  
  <p>So I tried doing something like this</p>
  
  <pre><code>granularity_val = 'year'
  dates = df[1].dt.granularity_val.values.tolist()
  </code></pre>
  
  <p>But it throws an error like below</p>
  
  <pre><code>AttributeError: 'DatetimeProperties' object has no attribute 'granularity_val'
  </code></pre>
  
  <p>I understand it is trying to treat the variable as an attribute of <code>dt</code> object of <code>pandas</code>. So how do I make python understand that it needs to treat <code>granularity_val</code> not as an attribute but as a variable value?</p>