Python从时间戳获取小时 [英] Python getting hour from from timestamp
问题描述
我需要基于小时对时间戳进行分类,例如,如果它是在上午7点到上午9点之间,则应该是上午.我有从csv文件中提取的时间戳,我只需要小时,因此可以使用if语句对数字进行分类.
I need to classify timestamps based on the hour, for example if it is between 7 AM and 9 AM, it will be morning. I have timestamps that I take from my csv file and I need to get only hour so I can classify the number with if statements.
我将使用 date 列中的时间戳记,并创建一个名为 hour ,
I will take the timestamps from date column and create a new column named hour,
df['hour'] = df.date.dt.hour
但是它给了我以下错误: AttributeError:只能使用具有datetimelike值的.dt访问器
but it gives me the following error: AttributeError: Can only use .dt accessor with datetimelike values
时间戳如下:2016-03-14 17:24:55
Timestamps are like the following: 2016-03-14 17:24:55
推荐答案
我不确定 df
是哪种对象,但是您可以将时间戳转换为 datetime
对象然后使用datetime对象的属性访问时间戳属性:
I'm not sure what kind of object is df
but you could convert timestamps to datetime
objects and then use attributes of datetime objects to access timestamp attributes:
from datetime import datetime
d = datetime.strptime('2016-03-14 17:24:55', '%Y-%m-%d %H:%M:%S')
df['hour'] = d.hour
您可以在此链接上阅读有关 datetime
模块的更多信息
You can read more about datetime
module at this link
这篇关于Python从时间戳获取小时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!