在df中查找所有时间戳列并将其转换为datatime

2024-09-28 22:40:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个df,它在下面的表单中有几列timestmap

2021-01-21T12:25:21.000Z

转换为日期时间

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

有没有办法一次转换所有的timestamp列,而不手动指定每个列

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

enter image description here


Tags: 表单df时间手动timestampmsseriespd
1条回答
网友
1楼 · 发布于 2024-09-28 22:40:04

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

# 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')

相关问题 更多 >