将int64转换为格式为%H:%M的datetime

2024-09-28 01:27:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下数据帧:

df_h00 = df.copy()
tt = df_h00.set_index('username').post_time_data.str.extractall(r'totalCount\":([^,}]*)')
tt['index']=tt.index
tt[['user','hour']]=pd.DataFrame(tt['index'].values.tolist(),
                        index=tt.index)
tt = tt.drop(['index'], axis=1)
tt.columns = ['totalCount', 'user', 'hours']
tt.head()

                totalCount  user   hours
username  match         
lowi      0        15       lowi    0
          1        11       lowi    1
          2        2        lowi    2
          3        0        lowi    3
          4        0        lowi    4

我想将tt['hours']列non-null int64转换为格式为“%H:%M”的日期时间。 我尝试了以下代码:

tthour = tt['hours']
tthour = pd.to_datetime(tthour, format='%H', errors='coerce')
tthour = tthour.to_frame()
tthour.head()

                        hours
username  match 
lowi       0    1900-01-01 00:00:00
           1    1900-01-01 01:00:00
           2    1900-01-01 02:00:00
           3    1900-01-01 03:00:00
           4    1900-01-01 04:00:00

但是,我只想要“%H:%M”。所以预期的输出是这样的:

                  hours
username  match 
lowi       0      00:00
           1      01:00
           2      02:00
           3      03:00
           4      04:00

Tags: to数据dfindexmatchusernameheadpd
1条回答
网友
1楼 · 发布于 2024-09-28 01:27:51

python中不存在所需格式的Datetimes

^{}或字符串^{}关闭timedeltas

tt = pd.DataFrame({'hours':np.arange(5)})
tt['td'] = pd.to_timedelta(tt['hours'].astype(str).str.zfill(2) + ':00:00',  errors='coerce')
tt['str'] = tt['hours'].astype(str).str.zfill(2) + ':00'
print (tt)
   hours       td    str
0      0 00:00:00  00:00
1      1 01:00:00  01:00
2      2 02:00:00  02:00
3      3 03:00:00  03:00
4      4 04:00:00  04:00

相关问题 更多 >

    热门问题