我的数据框中有一列我想将其转换为时间戳。然而,它的格式有点奇怪,我正在努力操纵。该列的格式为 HHMMSS,但不包含前导零。
例如,对于应该为“00:03:15”的时间,数据帧具有“315”。我想将后者转换为与前者类似的时间戳。以下是该列的插图:
message_time
25
35
114
1421
...
235347
235959
谢谢
最佳答案
使用Series.str.zfill
添加前导零,然后 to_datetime
:
s = df['message_time'].astype(str).str.zfill(6)
df['message_time'] = pd.to_datetime(s, format='%H%M%S')
print (df)
message_time
0 1900-01-01 00:00:25
1 1900-01-01 00:00:35
2 1900-01-01 00:01:14
3 1900-01-01 00:14:21
4 1900-01-01 23:53:47
5 1900-01-01 23:59:59
我认为最好通过 to_timedelta
创建时间增量:
s = df['message_time'].astype(str).str.zfill(6)
df['message_time'] = pd.to_timedelta(s.str[:2] + ':' + s.str[2:4] + ':' + s.str[4:])
print (df)
message_time
0 00:00:25
1 00:00:35
2 00:01:14
3 00:14:21
4 23:53:47
5 23:59:59
关于python - 如何将非正统格式的时间转换为pandas数据帧中的时间戳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56970497/