我在 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/