我有一个数据框,它存储了文本文件中的一些信息,这些信息给了我关于执行作业的详细信息。
我将所有这些信息存储在一个名为"df_tmp“的数据帧中。在该数据帧上,我有一列"end_Date“,我想在其中存储文件的结束日期,这是我的文件的最后一行,但是如果在数据帧中我没有任何值,我想存储current_time。
假设我的文件中的信息在以下变量上:
string_from_my_file = 'Execution time at 2019/10/14 08:06:44'
我需要的是:
如果我的手册文件在最后一行没有任何日期,我想存储current_time。为此,我尝试使用以下代码:
now = dt.datetime.now()
current_time = now.strftime('%H:%M:%S')
df_tmp['end_date'] = df_tmp['end_date'].fillna(current_time).apply(lambda x: x.strftime('%Y-%m-%d %H:%M:%S') if not pd.isnull(x) else pd.to_datetime(re.search("([0-9]{4}\/[0-9]{2}\/[0-9]{2}\ [0-9]{2}\:[0-9]{2}\:[0-9]{2})", str(df_tmp['string_from_my_file']))[0]))
但是,它给出了以下错误:
builtins.AttributeError: 'str' object has no attribute 'strftime'
我做错了什么?
谢谢
发布于 2019-10-15 07:17:36
试试这个:
df_tmp['end_date'] = df_tmp['end_date'].fillna(current_time).apply(lambda x: pd.to_datetime(x).strftime('%Y-%m-%d %H:%M:%S') if not pd.isnull(x) else pd.to_datetime(re.search("([0-9]{4}\/[0-9]{2}\/[0-9]{2}\ [0-9]{2}\:[0-9]{2}\:[0-9]{2})", str(df_tmp['string_from_my_file']))[0]))
在此部分lambda x: pd.to_datetime(x).strftime('%Y-%m-%d %H:%M:%S'
中,需要将x
更改为datetime以应用strftime()
。
错误的可能原因是:即使end_date
列的类型为datetime,但您正在使用str
类型的值填充该列。这正在更改end_date
列的数据类型。
https://stackoverflow.com/questions/58389078
复制相似问题