Search code examples
pythonpandasdatetimefeature-engineering

How to find the difference between time and feed the difference in a new column?


I have a dataframe trades_df which looks like this -

Open Time Open Price Close Time
19-08-2020 12:19 1.19459 19-08-2020 12:48
28-08-2020 03:09 0.90157 08-09-2020 12:20

It has columns open_time and close_time in the format 19-08-2020 12:19. I want to make a new column 'time_spent' which would be the difference between 'close_time' and 'open_time'.


Solution

  • Is this what you are trying to do?

    df = pd.DataFrame({
        'Start_Time' : ['19-08-2020 12:19', '28-08-2020 03:09'],
        'End_Time' : ['19-08-2020 12:48', '28-08-2020 06:03']
    })
    
    df['Start_Time'] = pd.to_datetime(df['Start_Time'], infer_datetime_format=True)
    df['End_Time'] = pd.to_datetime(df['End_Time'], infer_datetime_format=True)
    df['Time_Difference'] = df['End_Time'] - df['Start_Time']
    df