Federico Gentile
Federico Gentile

Reputation: 5940

Subtract time value to column of times in Pandas

I have a column of times like so

df = pd.DataFrame({'times':['10:59:20.1647', '11:05:46.2258', '11:10:59.4658']})

my goal is to subtract to all this times the the first time. In order to do so, I converted the column to datetime.time type and subtracted the first value to all the column:

pd.to_datetime(df['times']).dt.time - pd.to_datetime(df['times']).dt.time.iloc[0]

However, by doing so I get an error:

TypeError: unsupported operand type(s) for -: 'datetime.time' and'datetime.time'

Could you suggest a smart and elegant way in order to achieve my goal?

Upvotes: 1

Views: 1443

Answers (1)

jezrael
jezrael

Reputation: 862741

Use timedeltas:

a = pd.to_timedelta(df['times'])
b =  a - a.iat[0]
print (b)
0          00:00:00
1   00:06:26.061100
2   00:11:39.301100
Name: times, dtype: timedelta64[ns]

And if need times:

c = pd.to_datetime(b).dt.time
print (c)
0           00:00:00
1    00:06:26.061100
2    00:11:39.301100
Name: times, dtype: object

print (c.apply(type))
0    <class 'datetime.time'>
1    <class 'datetime.time'>
2    <class 'datetime.time'>
Name: times, dtype: object

Another solution with output timedelta:

a = pd.to_datetime(df['times'])
b =  a - a.iat[0]
print (b)
0          00:00:00
1   00:06:26.061100
2   00:11:39.301100
Name: times, dtype: timedelta64[ns]

Upvotes: 1

Related Questions