I have a data that looks like this
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)]
I am using pandas to do some data wrangling. Now I need to get a list of dates from the data in certain formats like hour, month, year etc. So to extract dates from the data in month, this is what I do
import pandas as pd
import datetime
df = pd.DataFrame(data)
dates = df[1].dt.month.values.tolist()
So I get a list of months. But in the method df[1].dt.year.values.tolist(), I want to assign the granularity dynamically ie it could either be dt.month or dt.year based on the variable value.
Say I have a variable called granularity_val
So if granularity_val = 'year', I should do
dates = df[1].dt.year.values.tolist()
Similarly if granularity_val = 'month', I should do
dates = df[1].dt.month.values.tolist()
So I tried doing something like this
granularity_val = 'year'
dates = df[1].dt.granularity_val.values.tolist()
But it throws an error like below
AttributeError: 'DatetimeProperties' object has no attribute 'granularity_val'
I understand it is trying to treat the variable as an attribute of dt object of pandas. So how do I make python understand that it needs to treat granularity_val not as an attribute but as a variable value?