【问题标题】:pandas convert integer to time熊猫将整数转换为时间
【发布时间】:2020-08-21 06:34:22
【问题描述】:

我有像这样以秒为单位的时间列

100
100000
235900

我想转换成时间格式,即

00:01
01:00
23:59

我试过了

time = pd.to_datetime(temp['time'], format='%H%M%S').dt.time

但它会抛出

ValueError: time data '0' does not match format '%H%M%S' (match)

【问题讨论】:

    标签: pandas time


    【解决方案1】:

    使用Series.str.zfill 将整数转换为字符串:

    time = pd.to_datetime(temp['time'].astype(str).str.zfill(6), format='%H%M%S').dt.time
    print (time)
    0    00:01:00
    1    10:00:00
    2    23:59:00
    Name: time, dtype: object
    

    如果需要时间增量:

    s = temp['time'].astype(str).str.zfill(6)
    
    td = pd.to_timedelta(s.str[:2] + ':' + s.str[2:4] + ':' + s.str[4:])
    print (td)
    0   00:01:00
    1   10:00:00
    2   23:59:00
    Name: time, dtype: timedelta64[ns]
    

    或者:

    td= pd.to_timedelta(time.astype(str))
    print (td)
    0   00:01:00
    1   10:00:00
    2   23:59:00
    Name: time, dtype: timedelta64[ns]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-27
      • 2013-02-18
      • 2017-07-31
      相关资源
      最近更新 更多