Search code examples
pythonpython-3.xpandaspython-datetime

Subtracting datetime considering forward times?


I have below datetime columns, I am trying to subtract but am getting negative value, how can I just retrieve the absolute difference in minutes?

 start_time   |   end_time  | current_output
   23:19:29       00:00:02     -1399.450000


df['current_output'] = (pd.to_datetime(df.end_time) - pd.to_datetime(df.start_time))/np.timedelta64(1, 'm')



 start_time   |   end_time  | desired_output
       23:19:29       00:00:02     40.33

Thank you!


Solution

  • There's probably a better approach, but if the time-delta is negative you can add 1440 (number of minutes in 24 hours)

    import pandas as pd
    import numpy as np
    
    df = pd.DataFrame({
        'start_time':['23:19:29','12:20:00','12:00:00'],
        'end_time':['00:00:02','14:20:00','11:59:00'],
    })
    
    minutes_diff = (pd.to_datetime(df.end_time) - pd.to_datetime(df.start_time))/np.timedelta64(1, 'm')
    
    minutes_diff[minutes_diff < 0] += 1440
        
    df['diff'] = minutes_diff
    df
    

    Output:

    enter image description here