LearningSlowly
LearningSlowly

Reputation: 9451

Pandas .dt.hour formatting

I have a datetime64[ns] format object in a pandas dataframe.

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?

Upvotes: 6

Views: 17088

Answers (3)

Lion Nadej Ahmed
Lion Nadej Ahmed

Reputation: 21

you can convert it to object and then use str.split(' ') to divide the row into date section and time section, then you can assign each part to a column or replace the current one.

df['date'], df['hour'] = df['datetime'].str.split(' ', 1).str
print (df)
         datetime       date         hour
0 2015-10-19 01:00:00   2015-10-19   01:00:00
1 2015-10-19 01:50:00   2015-10-19   01:50:00

Upvotes: 0

piRSquared
piRSquared

Reputation: 294546

@jezrael has it covered... This answer will look just like .dt.time but be a string instead

df.assign(hour=df.datetime.dt.strftime('%H:%M:%S'))

             datetime      hour
0 2015-10-19 01:00:00  01:00:00

Upvotes: 2

jezrael
jezrael

Reputation: 863741

I think you need 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:

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

Upvotes: 12

Related Questions