pythonpandasdeltatimestep

Pandas: extract hour from timedelta


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'


Solution

  • Divide by np.timedelta64(1, 'h'):

    df1['B'] = df1['A'] / np.timedelta64(1, 'h')
    print (df1)
             A    B
    0 02:00:00  2.0
    1 01:00:00  1.0
    2 02:00:00  2.0
    3 03:00:00  3.0