Taylrl
Taylrl

Reputation: 3919

Convert string to datetime whilst skipping over nulls

I am trying to convert a field that contains a string that represents a date. i started off with the following code that first ensures the value is a string and then converts this into a string....... all good you might think!? (The string is in the form yyyymmdd)

def dateconvert(Start_date):
    Date_String = str(Start_date)
    dateconv = dt.datetime.strptime(Date_String, '%Y%m%d').strftime('%d/%m/%Y')
    return  dateconv

df['Newdates'] = df['Start_Date'].apply(dateconvert)

This however is giving me an error that states the following;

ValueError: unconverted data remains: .0

This I assumed might be because the value I am feeding in is a float so I added the following;

def dateconvert(Start_date):
    Start_date = int(Start_date)  
    Date_String = str(Start_date)
    dateconv = dt.datetime.strptime(Date_String, '%Y%m%d').strftime('%d/%m/%Y')
    return  dateconv

df['Newdates'] = df['Start_Date'].apply(dateconvert)

This however gives me

ValueError: cannot convert float NaN to integer

Due to the fact that there are Null values in this particular field.

I therefore tried the following but I still get the same error as before!

def dateconvert(Start_date):
    if Start_date is not None:   
        Start_date = int(Start_date)  
        Date_String = str(Start_date)
        dateconv = dt.datetime.strptime(Date_String, '%Y%m%d').strftime('%d/%m/%Y')
        return  dateconv

df['Newdates'] = df['Start_Date'].apply(dateconvert)

What I just want to be able to do is convert this string to a date, skipping over the nulls.

Thanks.

Upvotes: 0

Views: 292

Answers (1)

v.chaplin
v.chaplin

Reputation: 617

Could use try/catch.

def dateconvert(Start_date):

    try:

        Start_date = int(Start_date)  
        Date_String = str(Start_date)
        dateconv = dt.datetime.strptime(Date_String, '%Y%m%d').strftime('%d/%m/%Y')
        return  dateconv
    except ValueError:
        return Start_date #or '' or whatever you want to return for NULL

Upvotes: 1

Related Questions