我有一个具有以下列和数据类型的数据框架(test_df):
|     Column          |     Data Type    |
|---------------------|------------------|
|    flowId           |         object   |
|    flowName         |         object   |
|    executionId      |         object   |
|    startedAt        |         datetime64[ns, tzlocal()]       |
|    lastUpdatedAt    |         datetime64[ns, tzlocal()]       |
|    dataPullStartTime|         datetime64[ns, tzlocal()]       |
|    dataPullEndTime  |         datetime64[ns, tzlocal()]       |
|    bytesProcessed   |         float64       |
|    bytesWritten     |         float64       |
|    recordsProcessed |         float64       |在将此数据帧转换为JSON类型格式之前,我希望将datetime列更改为使用strftime字符串。
test_df[['startedAt','lastUpdatedAt', 'dataPullStartTime', 'dataPullEndTime']] = 
test_df[['startedAt','lastUpdatedAt', 
'dataPullStartTime','dataPullEndTime']].apply(datetime.strftime('%Y-%m-%d 
%H:%M:%S.%f'), axis=1)但是,我总是收到以下错误:
TypeError: descriptor 'strftime' for 'datetime.date' objects doesn't apply to a 'str' object我没有遇到这个问题,因为相关列的数据类型是datetime,而不是str。有人能帮忙吗?我已经从堆栈中尝试了多个解决方案,但是我无法解决这个问题。
提前感谢!
发布于 2022-05-09 13:26:01
您应该对每一列使用向量dt.strfime:
cols = ['startedAt','lastUpdatedAt', 'dataPullStartTime', 'dataPullEndTime']
df[cols] = df[cols].apply(lambda c: c.dt.strftime('%Y-%m-%d %H:%M:%S.%f'))或为就地修改:
cols = ['startedAt','lastUpdatedAt', 'dataPullStartTime', 'dataPullEndTime']
df.update(df[cols].apply(lambda c: c.dt.strftime('%Y-%m-%d %H:%M:%S.%f')))示例:
df = pd.DataFrame({'col1': ['2000-01-01'], 'col2': ['2022-01-01']})
df['col1'] = pd.to_datetime(df['col1'])
df['col2'] = pd.to_datetime(df['col2'])
print(df)
        col1       col2
0 2000-01-01 2022-01-01
cols = ['col1', 'col2']
df.update(df[cols].apply(lambda c: c.dt.strftime('%Y-%m-%d %H:%M:%S.%f')))
print(df)
                         col1                        col2
0  2000-01-01 00:00:00.000000  2022-01-01 00:00:00.000000发布于 2022-05-09 13:26:46
你可以一列一列地做。
   for col in ['startedAt','lastUpdatedAt', 'dataPullStartTime','dataPullEndTime'] : 
        test_df[col] = test_df[col].apply(lambda x: datetime.strftime(x, '%Y-%m-%d %H:%M:%S.%f'))发布于 2022-05-09 13:27:22
apply需要一个函数,而不是作为args的对象。
df["dataPullEndTime"].apply(lambda x: datetime.strftime(x, '%Y-%m-%d %H:%M:%S.%f'))再生产
datetime.strftime('%Y-%m-%d %H:%M:%S.%f')TypeError: descriptor 'strftime' requires a 'datetime.date' object but received a 'str'https://stackoverflow.com/questions/72172692
复制相似问题