Apr-30-2019, 05:33 PM
Hi,
I am trying to find the current month in a dataframe to pull other information from that specific month.
Datetime provides the month as a number. However, my dataframe has columns with the Month as a text (Jan, Feb, etc.)
How can I convert the value from datetime (= int) to the month's text so I can pull the month's information? Or is there a better way to do this?
(BTW, I ended up modifying my dataframe and naming the columns by numbers, instead of texts. But I will need to do the same thing again, and changing the header all the time is not feasible.)
Here is what I tried, but I keep receiving an error "TypeError: 'int' object is not iterable". Thank you for your help!
I am trying to find the current month in a dataframe to pull other information from that specific month.
Datetime provides the month as a number. However, my dataframe has columns with the Month as a text (Jan, Feb, etc.)
How can I convert the value from datetime (= int) to the month's text so I can pull the month's information? Or is there a better way to do this?
(BTW, I ended up modifying my dataframe and naming the columns by numbers, instead of texts. But I will need to do the same thing again, and changing the header all the time is not feasible.)
Here is what I tried, but I keep receiving an error "TypeError: 'int' object is not iterable". Thank you for your help!
#Create date now = datetime.datetime.now() #Create a variable with today's date day = now.day month = now.month year = now.year dict_month = {1:'Jan',2:'Feb',3:'Mar',4:'Apr',5:'May',6:'Jun',7:'Jul',8:'Aug',9:'Sep',10:'Oct',11:'Nov',12:'Dec'} def replace_month(currentmonth,dictionary): for item in month: if item in dictionary.keys(): currentmonth = currentmonth.replace(item,dictionary[item]) return currentmonth replace_month(month,dict_month)OUTPUT
Error:---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-58-21c990b207f8> in <module>()
----> 1 replace_month(month,dict_month)
<ipython-input-56-94280bfdaaac> in replace_month(currentmonth, dictionary)
1 def replace_month(currentmonth,dictionary):
----> 2 for item in month:
3 if item in dictionary.keys():
4 currentmonth = currentmonth.replace(item,dictionary[item])
5 return currentmonth
TypeError: 'int' object is not iterable