Skip to content Skip to sidebar Skip to footer

Convert Dataframe Column To Datetime Only If Length Of String Is Not Zero

I'd like to convert a dataframe column which has a date string. But in some cases, the date string might be empty due to certain conditions. So I just want all the other rows in th

Solution 1:

Two steps,

first lets create a series with your datetimes and coerce the bad values into NaTs

s = pd.to_datetime(data['etime'],errors='coerce',format='%Y%m%d%H%M%S')

second, lets find any values that aren't NaT and replace them with your target formatting.

data.loc[~s.isna(),'etime'] = s.dt.strftime('%Y-%m-%d %H:%M')

   day             etime
0152020-08-1123:521172202020-08-1121:52314202008112652054252020-08-1123:52
  • assuming 26 is a typo in your hour column at index 3.

Solution 2:

You can try something like:

df["etime"] =  df["etime"].apply(lambda x: pd.to_datetime(x,errors='ignore').strftime('%Y-%m-%d %H:%M') if len(x) !=0 else"----")

Post a Comment for "Convert Dataframe Column To Datetime Only If Length Of String Is Not Zero"