Pandas: extract hour from timedelta

FaCoffee picture FaCoffee · Aug 30, 2018 · Viewed 9.6k times · Source

This answer explains how to convert integers to hourly timesteps in Pandas. I need to do the opposite.

My dataframe df1:

   A
0  02:00:00
1  01:00:00
2  02:00:00
3  03:00:00

My expected dataframe df1:

   A         B
0  02:00:00  2
1  01:00:00  1
2  02:00:00  2
3  03:00:00  3

What I am trying:

df1['B'] = df1['A'].astype(int)

This fails because: TypeError: cannot astype a timedelta from [timedelta64[ns]] to [int32]

What is the best way to do this?

EDIT

If I try df['B'] = df['A'].dt.hour, then I get: AttributeError: 'TimedeltaProperties' object has no attribute 'hour'

Answer

EdChum picture EdChum · Aug 30, 2018

You can use dt.components and access the hours column:

In[7]:
df['B'] = df['A'].dt.components['hours']
df

Out[7]: 
         A  B
0 02:00:00  2
1 01:00:00  1
2 02:00:00  2
3 03:00:00  3

the timedelta components returns each component as a column:

In[8]:
df['A'].dt.components

Out[8]: 
   days  hours  minutes  seconds  milliseconds  microseconds  nanoseconds
0     0      2        0        0             0             0            0
1     0      1        0        0             0             0            0
2     0      2        0        0             0             0            0
3     0      3        0        0             0             0            0