python - 如何将非正统格式的时间转换为pandas数据帧中的时间戳

标签 python pandas datetime timestamp

我的数据框中有一列我想将其转换为时间戳。然而,它的格式有点奇怪,我正在努力操纵。该列的格式为 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/

相关文章:

python - 打开文件以使用truncate进行读写

python - 如何检查是否所有数据都通过 Python 中的 TCP 套接字接收到

python - 将 pandas 中的 float 转换为字符串时精度损失

python - 为什么我收到此错误关键字 :Borough

PHP时间戳到DateTime

Python 'startswith' 等同于 SqlAlchemy

python 字典和函数不起作用

python - 根据日期列范围将列添加到数据框

c# - EF5;将 20100326 之类的字符串转换为 2010/03/26

php - 在 Codeigniter 3.0.6 中插入当前日期时间