-2

I am facing problem while finding the duration. The df is

data ={ 
    'initial_time': ['2019-05-21 22:29:55','2019-10-07 17:43:09','2020-12-13 23:53:00','2018-04-17 23:51:23','2016-08-31 07:40:49'],
    'final_time' : ['2019-05-22 01:10:30','2019-10-07 17:59:09','2020-12-13 00:30:10','2018-04-18 01:01:23','2016-08-31 08:45:49'],
    'duration' : [0,0,0,0,0]
      }
df =pd.DataFrame(data)
df

Output:

       initial_time            final_time     duration
0   2019-05-21 22:29:55   2019-05-22 01:10:30   0
1   2019-10-07 17:43:09   2019-10-07 17:59:09   0
2   2020-12-13 23:53:00   2020-12-13 00:30:10   0
3   2018-04-17 23:51:23   2018-04-18 01:01:23   0
4   2016-08-31 07:40:49   2016-08-31 08:45:49   0

The output I'm expecting is total duration i.e final_time - initial_time.

Note : It consist values whose initial and final time comes on different dates(row 1).

Abhi
  • 41
  • 6
  • convert all of your time into hours and then do it. Could you please specify the format of the time you are using, is it DD-MM-YYYY? – jimmie_roggers Jul 28 '21 at 09:49
  • @jimmie_roggers time format is "pd.to_datetime" – Abhi Jul 28 '21 at 09:51
  • Does this answer your question? [Calculate Pandas DataFrame Time Difference Between Two Columns in Hours and Minutes](https://stackoverflow.com/questions/22923775/calculate-pandas-dataframe-time-difference-between-two-columns-in-hours-and-minu) – shoaib30 Jul 28 '21 at 09:58

1 Answers1

0

The problem can be broken down into 3 parts:

  1. convert strings to datetime objects
  2. write function that compute duration between 2 datetime objects
  3. apply the function to the new column of your dataframe

  1. datetime_object = datetime.strptime('2019-05-21 22:29:55', '%Y-%m-%d %H:%M:%S')
  2. How do I find the time difference between two datetime objects in python?
3) df['duration'] = df.apply(lambda row: getDuration(row['initial_time'], row['final_time'], 'seconds'), axis=1)
marco sala
  • 11
  • 1