Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas .dt.hour formatting

Tags:

python

pandas

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?

like image 973
LearningSlowly Avatar asked Mar 23 '17 13:03

LearningSlowly


2 Answers

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
like image 168
jezrael Avatar answered Oct 16 '22 21:10

jezrael


@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
like image 43
piRSquared Avatar answered Oct 16 '22 21:10

piRSquared