gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 20:33:22 24 4
gpt4 key购买 nike

我有以下数据框:

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com