YNR
YNR

Reputation: 875

How to convert string data with variable format to datetime?

I have a Pandas dataframe that has a column of time in string format as below:

 id       playTime

 12       1d 13h 23m
 13      42d 22h 47m
 14       7d 16h 31m
 15        1h 26m 6s 
 16           9d 58m

I tried pd.to_datetime(df['playTime'], format='%j%H%M%S') but it shows time data does not match format '%j%H%M%S' (match). In the end, I'd like to convert thedf['playTime']values to seconds.

Upvotes: 2

Views: 74

Answers (2)

jezrael
jezrael

Reputation: 862641

I think need to_timedelta for Timedeltas with total_seconds:

df['playTime'] = pd.to_timedelta(df['playTime']).dt.total_seconds().astype(int)
print (df)
   id  playTime
0  12    134580
1  13   3710820
2  14    664260
3  15      5166
4  16    781080

Upvotes: 1

Jonathan DEKHTIAR
Jonathan DEKHTIAR

Reputation: 3536

Can you try this:

pd.to_datetime(df['playTime'], format='%j %H %M %S')

Upvotes: 0

Related Questions