Home > OS >  calculate time spent by subtracting two times
calculate time spent by subtracting two times

Time:06-16

I have a dataframe 'trades_df'. 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'. See the photo for reference. enter image description here

CodePudding user response:

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

CodePudding user response:

Your datetimes have days come first, so dayfirst should be True:

# use dayfirst argument to convert to correct datetimes
df['time_spent'] = pd.to_datetime(df.close_time, dayfirst=True) - pd.to_datetime(df.open_time, dayfirst=True)
  • Related