Jess Jess - 2 years ago 223
Python Question

Adding two time columns together in pandas dataframe?

I have the following data:

time_begin DRTN_IN_SCND
16:22:16 439
16:29:37 53
16:30:33 85

I would like to make a new column that adds time_begin and DRTN_IN_SCND (the duration in seconds) to create a new time.

I have tried:

df['new_time'] = df['time_begin'].apply(lambda x: (dt.datetime.combine(dt.datetime(1,1,1), x,) + dt.timedelta(seconds=df.DRTN_IN_SCND)).time())

This works if dt.timedelta(seconds=3) but does not work when I change to dt.timedelta(seconds=df.DRTN_IN_SCND). I get the following error.

TypeError: unsupported type for timedelta seconds component: Series

Does anyone know how to fix this or of another way to accomplish what I'm trying to do? Thanks!

Answer Source

You'll have to convert the DRTN_IN_SCND and time_begin to time deltas if you want to do properly calculations on the columns, pandas has to_timedelta which is pretty handy:

df['DRTN_IN_SCND'] = pd.to_timedelta(df['DRTN_IN_SCND'], unit='s')
df['time_begin'] = pd.to_timedelta(df['time_begin'])
df['new_time'] = df['time_begin'] + df['DRTN_IN_SCND']

This will give you the new column new_time:

   time_begin  DRTN_IN_SCND  new_time
0    16:22:16      00:07:19  16:29:35
1    16:29:37      00:00:53  16:30:30
2    16:30:33      00:01:25  16:31:58
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download