Python getting hour from from timestamp

13,826

Solution 1

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

You can read more about datetime module at this link

Solution 2

You need to convert your 'date' columnn to a datatime object first:

df['date'] = pd.to_datetime(df['date'], format='%Y-%m-%d %H:%M:%S')
df['hour'] = df['date'].dt.hour
Share:
13,826
S.Shiro
Author by

S.Shiro

Updated on June 08, 2022

Comments

  • S.Shiro
    S.Shiro almost 2 years

    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.

    I will take the timestamps from date column and create a new column named hour,

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

    but it gives me the following error: AttributeError: Can only use .dt accessor with datetimelike values

    Timestamps are like the following: 2016-03-14 17:24:55