7

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

1
  • you have to first convert date-column to datetime like this: df['date'] = pd.to_datetime(df['date']) Commented Mar 18, 2019 at 20:07

4 Answers 4

8

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

0

You need to create a datetime object with the timestamp string extracted from your CSV input data:

In [1]: import datetime

In [2]: s = '2016-03-14 17:24:55'

In [3]: d = datetime.datetime.fromisoformat(s)

In [4]: d.hour
Out[4]: 17

Comments

0

The reason why you get an AttributeError: Can only use .dt accessor with datetimelike values is most likely because that particular series is not of datetime object type.

Like the error states, .dt attribute is available for datetime objects. So first thing to do is check the type of entries. Suppose the values are not datetime objects then to convert it,

specify datetime_format = '%Y-%m-%d %H:%M:%S' and use .dt the following way to get time values:

data['start_datetime'] = pd.to_datetime(data['start_datetime'], format=datetime_format)
h = data['start_datetime'].dt.hour
m = data['start_datetime'].dt.minute
s = data['start_datetime'].dt.second

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.