Python Forum
Replacing an integer by looking at a dictionary - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Replacing an integer by looking at a dictionary (/thread-17950.html)



Replacing an integer by looking at a dictionary - wendysling - Apr-30-2019

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!

#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



RE: Replacing an integer by looking at a dictionary - Larz60+ - Apr-30-2019

import datetime

today = datetime.datetime.today()
print('ISO     :', today)
print('Month: {:%b}'.format(today))
output:
Output:
ISO : 2019-04-30 14:13:25.444963 Month: Apr



RE: Replacing an integer by looking at a dictionary - nilamo - Apr-30-2019

return dictionary[currentmonth]?


RE: Replacing an integer by looking at a dictionary - wendysling - May-02-2019

This is helpful to change the number for a text.