【问题标题】:how to convert time in unorthodox format to timestamp in pandas dataframe如何将非正统格式的时间转换为熊猫数据框中的时间戳
【发布时间】:2019-11-20 01:39:03
【问题描述】:

我的数据框中有一列要转换为时间戳。但是,我正在努力操纵它的格式有点奇怪。该列采用 HHMMSS 格式,但不包括前导零。

例如,对于应为“00:03:15”的时间,数据帧具有“315”。我想将后者转换为类似于前者的时间戳。这是该列的插图:

message_time
25
35
114
1421
...
235347
235959

谢谢

【问题讨论】:

  • 25 是指2:05:002:00:0500:02:05 还是00:00:25

标签: python pandas datetime timestamp


【解决方案1】:

使用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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-13
    • 2021-09-23
    • 2016-03-27
    • 1970-01-01
    • 2017-04-13
    • 2011-08-05
    • 2019-04-26
    相关资源
    最近更新 更多