-1

These are two columns(A & B) in a python data frame

column df['A']

0 2021-05-19 11:21:29.463

1 2021-05-19 11:21:39.127

column df['B']

0 2021-05-19 11:19:27.217

1 2021-05-19 11:19:40.000

by subtracting these two columns df['A'] - df['B'] I need to get minutes and seconds

02:02

01:59

or at least below format

00:02:02

00:01:59

Thomas
  • 174,939
  • 50
  • 355
  • 478
  • 1
    please don't [duplicate your question](https://stackoverflow.com/q/68081772/10197418) - and see my comment there. – FObersteiner Jun 22 '21 at 11:04

1 Answers1

0

This should do it:

df['A'] = pd.to_datetime(df['A'])
df['B'] = pd.to_datetime(df['B'])
def date_string(a,b):
    td = (a - b)/np.timedelta64(1, 's')
    td = str(datetime.timedelta(seconds=td))
    return(td[:-7])
df['diff'] = df.apply(lambda x: date_string(x.A, x.B), axis=1)
le_camerone
  • 630
  • 5
  • 17
  • 1
    not need for typecasting here; subtracting the two datetime columns already gives you timedelta. btw. the OP is looking to *format* the output as well – FObersteiner Jun 22 '21 at 11:11
  • Not sure I understand. Isn't that the format they wanted? Also, are you assuming that the dates are already in datetime format? If they came from an excel file that might not be the case. @MrFuppes – le_camerone Jun 22 '21 at 11:17
  • conversion to datetime might be necessary, yes. but timedelta is not a format, it's a datatype. the OP wants a format "HH:MM:SS" or "MM:SS" (the datatype would be string then). – FObersteiner Jun 22 '21 at 11:19
  • @MrFuppes and OP. I have changed my answer in response to comments. – le_camerone Jun 22 '21 at 11:48
  • Please accept my answer if it has solved your problem. – le_camerone Jul 07 '21 at 11:49