Search code examples
pythondatedatetimeseriescallable

Python Dataframe: Extract Date from Datetime field -- 'Not Callable' Error


Updated Follow-up Question:

Error received after running code below: UnboundLocalError: local variable 'month_name' referenced before assignment

enter image description here

I have an object column that I converted into datetime successfully called "dtin". Below is what the data looks like:

enter image description here

I want to create a new column that extracts out just the month from the dtin column (see screen shot).

Below is the code I tried and the resulting error:

enter image description here

Any help is greatly appreciated.


Solution

  • As per my comment above, you need to remove the () like so.

    df_EVENT4_6['start_month'] = df_EVENT4_6['dtin'].dt.month
    

    This is because 'month' is not a function or method but a property. The () is trying to call something that can't be called.

    There are a number of ways you could change to the month name. I would probably define a function and use the apply method.

    def month_change(mnum):
        if mnum == 1:
            mname='Jan'
        elif .....
        return(mname)      
    
     df_EVENT4_6['dtin']=df_EVENT4_6['dtin'].apply(month_change)
    

    UPDATE

    My bad, you need to apply it to the other Series.

    def month_change(mnum):
        if mnum == 1:
            mname='Jan'
        elif .....
        return(mname)
    
     df_EVENT4_6['start_month'] = df_EVENT4_6['dtin'].dt.month
    
     df_EVENT4_6['start_month']=df_EVENT4_6['start_month'].apply(month_change)