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?
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
@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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With