仅当字符串的长度不为零时才将dataframe列转换为datetime

问题描述

我想转换一个带有日期字符串的数据框列。但是在某些情况下,由于某些条件,日期字符串可能为空。因此,我只想将该列中的所有其他行都转换为日期时间格式,但该特定列中的行可能为空。有可能吗?

到目前为止我已经尝试过:

选项1:

df['etime'] = pd.to_datetime(df['etime'],errors='ignore').dt.strftime('%Y-%m-%d %H:%M')

选项2:

    for ind in df.index:
        if (df['etime'].str.len()[ind] == 0) :
            df.loc[ind,'etime'] = "----"
        else:
           df.loc[ind,'etime'] = <need to convert this row to datetime>

请提供您的建议。

数据帧示例:

data = pd.DataFrame({

    'day' : [15,17,20,14,25],'etime': ["20200811235205","","20200811215205","20200811225205","20200811235203"]

})

解决方法

您可以尝试类似的操作:

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

两步,

首先让我们用您的日期时间创建一个序列,并将错误值强制转换为NaTs

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

第二秒钟,让我们查找所有非NaT的值,并将其替换为目标格式。

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

   day             etime
0   15  2020-08-11 23:52
1   17                  
2   20  2020-08-11 21:52
3   14    20200811265205
4   25  2020-08-11 23:52
  • 假设您小时栏中的26是索引3的错字。