如何在 Pandas 中将 4 位数字转换为小时:分钟时间格式

Nat*_*bsi 4 python time datetime pandas

我有一个由小时和分钟组成的 4 位字符串格式的时间。例如,1608 需要转换为 => 16:08

数据采用熊猫数据框的形式,我尝试过:

     A    st_time
1    23   1608
2    12   1635
3    18   1654
4    38   1705
Run Code Online (Sandbox Code Playgroud)

我尝试使用:

df.st_time.to_datetime().strftime('%h-%m') 
Run Code Online (Sandbox Code Playgroud)

但是,它会引发错误。

AttributeError: 'Series' object has no attribute 'to_datetime'
Run Code Online (Sandbox Code Playgroud)

piR*_*red 5

您需要pd.to_datetime通过将系列传递df.st_time给它来使用。完成后,您可以访问该time组件。

df.assign(newtime=pd.to_datetime(df.st_time, format='%H%M').dt.time)

    A  st_time   newtime
1  23     1608  16:08:00
2  12     1635  16:35:00
3  18     1654  16:54:00
4  38     1705  17:05:00
Run Code Online (Sandbox Code Playgroud)

但是,如果您想要返回具有指定格式的字符串。

df.assign(newtime=pd.to_datetime(df.st_time, format='%H%M').dt.strftime('%H:%M'))

    A  st_time newtime
1  23     1608   16:08
2  12     1635   16:35
3  18     1654   16:54
4  38     1705   17:05
Run Code Online (Sandbox Code Playgroud)