1

I have a pandas dataframe which has a 'Time' column which has rows like 13:50:00(it is of type string).Now I have a time of the format and value 21:21:21.I want to subtract the two.

Now I did abs(datetime.strptime(a, '%H:%M:%S').time()- recording_start_time)) which is still giving me the error

print(abs(datetime.strptime(a, '%H:%M:%S').time()- recording_start_time))
TypeError: unsupported operand type(s) for -: 'datetime.time' and 'datetime.time'

My code looks like-

 min_time_diff = abs(df3.loc[cond & cond2 ]['Time'].apply(lambda x: datetime.strptime(x, '%H:%M:%S').time()- recording_start_time))

so I need a cleaner solution than the subtract two times in python provided here as it is searching through all the rows in 'Time' column and subtracting from a fixed value.

ubuntu_noob
  • 2,305
  • 6
  • 23
  • 64

1 Answers1

2

You can convert to datetime, subtract from a timedelta and get back to time-only series by using .dt accessor

delta = datetime.timedelta(hours=21, minutes=21, seconds=21)
diff = pd.to_datetime(df.t, format="%H:%M:%S") - delta
>>> diff.dt.time

Example:

df = pd.DataFrame({'t':[time(2),time(8)]})

    t
0   02:00:00
1   08:00:00

d = pd.to_datetime(df.t, format="%H:%M:%S") - datetime.timedelta(minutes=1, seconds=1, hours=1)
d.dt.time

0    00:58:59
1    06:58:59
Name: t, dtype: object
rafaelc
  • 57,686
  • 15
  • 58
  • 82
  • my fixed variable is recording_start_time which has datatype datetime.time and the column ['Time'] has the format string...can you show how it is applicable in my case? – ubuntu_noob Jul 10 '18 at 01:03
  • @ubuntu_noob the same code should work for your case too :) just create a `datetime.timedelta` from your `time` object, doing `datetime.timedelta(hours= recording_start_time.hour, minutes = recording_start_time.minutes, ...` ) etc – rafaelc Jul 10 '18 at 01:03
  • Could you explain how to convert the values in 'Time' column df.t? – ubuntu_noob Jul 10 '18 at 01:06
  • I am saying my column ['Time'] has values in string format 15:30:00...and you are using df.t in your solution – ubuntu_noob Jul 10 '18 at 03:37