Search code examples
python-3.xpandas

How can explain with text difference time in Python?


I have dataframe and it has a time diffrence column. The column has like bellow values. I would like to create a new column and write in it like someting that: 1 hour, 11 minutes, 45 seconds. How to do that simple way on Python?

20   0 days 01:11:45
21   0 days 01:11:45
22   0 days 01:11:45
23   0 days 01:11:45
24   0 days 01:11:45
25   0 days 01:11:45
26   0 days 01:11:45
27   0 days 01:11:45
28   0 days 01:11:45
29   0 days 01:11:45

I am new at pyhton so I do have any idea what I can try.


Solution

  • as far i understand your query i assume your last column name is 'time' then for new column('time_components') you can create like follow

    df['time'] = pd.to_timedelta(df['time'])
    
    # Extract hours, minutes, and seconds into a new column
    df['time_components'] = df['time'].dt.components['hours'].astype(str) + ' hours, ' + df['time'].dt.components['minutes'].astype(str) + ' minutes, ' + df['time'].dt.components['seconds'].astype(str) + ' seconds'