Pandas .dt.hour 格式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42977395/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pandas .dt.hour formatting
提问by LearningSlowly
I have a datetime64[ns]
format object in a pandas dataframe.
我datetime64[ns]
在Pandas数据框中有一个格式对象。
I can use this column to compute the hour via:
我可以使用此列通过以下方式计算小时:
df['hour'] = df['datetime'].dt.hour
This returns an integer. e.g :
这将返回一个整数。例如:
datetime hour
19-10-2015 2015-10-19 01:00:00 1
What is the easiest way to output the hour
column in the 01:00:00
time format?
hour
以01:00:00
时间格式输出列的最简单方法是什么?
回答by jezrael
I think you need dt.time
:
我认为你需要dt.time
:
df['hour'] = df['datetime'].dt.time
print (df)
datetime hour
0 2015-10-19 01:00:00 01:00:00
But if need truncate datetimes to hours:
但如果需要将日期时间截断为小时:
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
A bit hack - strftime
and add string :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
回答by piRSquared
@jezrael has it covered... This answer will look just like .dt.time
but be a string instead
@jezrael 已经涵盖了......这个答案看起来就像.dt.time
是一个字符串
df.assign(hour=df.datetime.dt.strftime('%H:%M:%S'))
datetime hour
0 2015-10-19 01:00:00 01:00:00