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

Question:

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’.

Asked By: Atif

||

Answers:

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
Answered By: ArchAngelPwn

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)
Answered By: not a robot