Reputation: 45
I have a column in a pandas dataframe that looks like this:
Time:
16:45:15
16:45:31
16:45:59
.
.
I want to convert these times values into seconds and I did the following:
def get_sec(arr):
h,m,s = arr.split(':')
return int(h) * 3600 + int(m) * 60 + int(s)
sec_val = []
for i in range(len(df['Time'])):
sec_val.append(get_sec(df['Time'][i]))
and it gives this error:
'datatime.time' object has no attribute 'split'
Although if I used the same code for one string it works, but when I use it in a for loop it gives this error, any idea on how to solve it?
Thanks
Upvotes: 0
Views: 55
Reputation: 493
In [24]: df['TimeInSeconds'] = df['Time'].apply(lambda x : x.hour *3600 + x.minute * 60 + x.second )
Looks like your column is type datetime.time so you can directly use it's attributes like hour , minute , second rather than doing string split as above. hope it helps :)
Edit:
In case of string we can convert all in time objects then use the apply
import datetime
In [38]: df['Time' ] = df['Time'].astype(str).apply(lambda x : datetime.datetime.strptime(x, '%H:%M:%S' ).time() )
In [39]: df['TimeInSeconds'] = df['Time'].apply(lambda x : x.hour *3600 + x.minute * 60 + x.second )
Upvotes: 2