NaTType' object has no attribute 'dt' error when comparing null and not null

Viewed 296

Stack overflow!

I am trying to create a column using the defined function below. The goal is to count the number of days between dates based on the condition of 3 columns. However I am getting an error: NaTType' object has no attribute 'dt'

def onhire_counter(df):
    """returns col, num of days (int) item is onhire"""
    today = datetime.today() 
    
    if df['DisCompleteDate'] and df['OffHire'] is pd.NaT:
        return (today - df['ErCompleteDate']).dt.days
    
    elif df['DisCompleteDate'] is not pd.NaT and df['OffHire'] is pd.NaT:
        return (df['DisCompleteDate'] - df['ErCompleteDate']).dt.days
    
    elif df['DisCompleteDate'] is pd.NaT and df['OffHire'] is not pd.NaT:
        return (df['OffHire'] - df['ErCompleteDate']).dt.days
    
    else:
        return 0

df_hire['days_onhire'] = df_hire.apply(onhire_counter, axis = 1)

I have also tried .isnull & .notnull

Thanks for your help.. You are awesome!

1 Answers

Your issue seems like you have a NaT in your ErCompleteDate column. Any datetime or timestamp subtracted by a NaT will produce a NaT. An if statement at the start of the function can catch this out.

if df["ErCompleteDate"] is pd.NaT: return 0 # Or None depending on your case
Related