'How to convert into datetime pands df with NaNs

I have a Pandas Dataframe that looks like following:

|        dates         |
|----------------------|
|                  NaN |
| 2021-12-09T22:00:10Z |
|                  NaN |
|  2018-12-31 00:00:00 |
| 2021-12-09T22:00:10Z |

What I'm trying to do is applying same format to all those dates ignoring all NaN values. The desired output:

|        dates        |
|---------------------|
|                 NaN |
|2021-12-09 22:00:10  |
|                 NaN |
| 2018-12-31 00:00:00 |
| 2021-12-09 22:00:10 |

I have tried to do something similar to this but without success:

df.assign(dates=pd.to_datetime(df.dates, errors='ignore').dt.strftime("%Y-%m-%d %H:%M:%S"))

output:

AttributeError: Can only use .dt accessor with datetimelike values

Looks like the NaN's are still bothering

The approach I have followed so far is to create a function that is insanciated within a lambda. Inside that function I distinguish if the input value is NaN or not. In case it is not, I apply the formatting to the date:

def formatting(date: str) -> str:
    if date not in ["nan", "None", "NaN", ""...]: #We can have also nans and nulls masked as Strings!!!!
        date_f = pd.to_datetime(date).strftime("%Y-%m-%d %H:%M:%S")
    else:
        date_f = np.nan
    return date_f


# and then call that method inside lambda
df.dates = df.dates.apply(lambda x: formatting(x))

Any suggestions on how to do this better?

Thanks!!!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source