gpt4 book ai didi

python - Pandas .dt.hour 格式

转载 作者:行者123 更新时间:2023-12-03 01:04:52 24 4
gpt4 key购买 nike

我在 pandas 数据框中有一个 datetime64[ns] 格式对象。

我可以使用此列通过以下方式计算小时:

df['hour'] = df['datetime'].dt.hour

这将返回一个整数。例如:

datetime                        hour
19-10-2015 2015-10-19 01:00:00 1

01:00:00 时间格式输出 hour 列的最简单方法是什么?

最佳答案

我认为你需要dt.time :

df['hour'] = df['datetime'].dt.time
print (df)
datetime hour
0 2015-10-19 01:00:00 01:00:00

但是如果需要将日期时间截断为小时:

df['hour'] = df['datetime'].values.astype('<M8[h]')
df['hour'] = df['hour'].dt.time
print (df)
datetime hour
0 2015-10-19 01:00:00 01:00:00
1 2015-10-19 01:50:00 01:00:00

有点黑客 - strftime并添加字符串 :00:00:

df['hour'] = df['datetime'].dt.strftime('%H').add(':00:00')
print (df)
datetime hour
0 2015-10-19 01:00:00 01:00:00
1 2015-10-19 01:50:00 01:00:00

关于python - Pandas .dt.hour 格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42977395/

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