簡體   English   中英

將int64轉換為日期時間,格式為%H:%M'

[英]Convert int64 to datetime with format %H:%M'

我有以下DataFrame:

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

我想將non-null int64列tt ['hours']轉換為日期時間,格式為“%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

預期格式的日期時間在python中不存在。

使用Series.str.zfill或字符串關閉to_timedeltato_timedelta

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM