0

I have a list of dictionaries:

mylist=
[{'Start Time': '08:13:40', 'End Time': '14:13:10'},
{'Start Time': '09:12:30', 'End Time': '08:07:45'},
{'Start Time': '12:03:20', 'End Time': '17:23:10'},
... 
{'Start Time': '08:23:40', 'End Time': '19:23:40'}]

I wanted to append a new column that records the time difference between Start Time and End Time, so I tried the following:

dfmylist['new'] = pd.to_datetime(dfmylist['End Time']) - pd.to_datetime(dfmylist['Start Time'])

If 'End Time' is smaller than Start Time', I want to add 24 hrs to End Time before I do the calculation. I know I need to simply add an if...else, but I tried several ways and none of them works.

Mary
  • 231
  • 1
  • 3
  • 12
  • You can do this with pandas' apply() function though have a look at this answer: https://stackoverflow.com/a/62968313/3500157 – Alexander B. Mar 01 '22 at 18:42

1 Answers1

1

one way is to add the if after your calculation:

[x if x>=pd.Timedelta(0) else x+pd.Timedelta(24, 'hours') for x in dfmylist['new']]
Ezer K
  • 3,637
  • 3
  • 18
  • 34