熊猫将整数转换为时间

时间:2020-08-21 06:34:22

标签: pandas time

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

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)

1 个答案:

答案 0 :(得分: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]