首页 > 解决方案 > 在 pandas df 中查找所有时间戳列并将其转换为数据时间

问题描述

我有一个 df,它在以下格式中有几列时间图

2021-01-21T12:25:21.000Z

转换为日期时间

pd.Series(df.lastModifiedDate).astype('datetime64[ms]')
2021-01-21 12:25:21

有什么方法可以一次转换所有时间戳列而不手动指定每一列?

只有突出显示的一个是时间戳

在此处输入图像描述

标签: pythonpandas

解决方案


您可以通过测试一行中每一列的格式来收集列名。也就是说,如果列值的字符串与某个模式匹配,则将该列添加到列列表中

# if the pattern is more complex, replace with regex or longer pattern
dtcols = [c for c in df.columns if str(df.iloc[0, df.columns.get_loc(c)]).endswith('0Z')]

# use to_datetime rather than astype, you have more control over conversion
df.loc[:, dtcols] = pd.to_datetime(df.loc[:, dtcols], errors='coerce')

推荐阅读