python - 将 int64 转换为日期时间,格式为 %H :%M'

标签 python pandas datetime timedelta

我有以下数据框:

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

我想将非空 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 中不存在您期望格式的日期时间。

关闭您需要的是timedeltas通过 to_timedeltaSeries.str.zfill或字符串:

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

关于python - 将 int64 转换为日期时间,格式为 %H :%M',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57335916/

相关文章:

Python - 如何只获得复数的实部

python - 如何在标题前使用配置行写入 csv 数据框

date - Google Calendar API 不接受具有正 UTC 偏移量的日期时间?

datetime - 为什么在使用请求时解析我的日期成功,但在使用 reqwests 时失败?

python - 在 Robot Framework 中运行测试套件

python - 单击应用程序时 Windows-Pyinstaller 错误 "failed to execute script "

python - Pandas dataframe 到以 ID 作为键的字典

python - 使用 secondary_y 轴绘制 groupby 数据

datetime - Coldfusion Now() 返回错误的分钟数

python - 使用 Beautifulsoup 解析 NELL 知识库页面