Python Forum
Replacing an integer by looking at a dictionary
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Replacing an integer by looking at a dictionary
#1
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
Reply
#2
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
Reply
#3
return dictionary[currentmonth]?
Reply
#4
This is helpful to change the number for a text.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Can a dictionary key be an integer? Pedroski55 7 17,205 Oct-05-2017, 05:54 AM
Last Post: buran

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020