Python Forum
How to get indices of minimum time difference - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: How to get indices of minimum time difference (/thread-30843.html)



How to get indices of minimum time difference - Mekala - Nov-09-2020

Hi,
I have below data:
df1:
time1 time2
2020/11/05 20:30:23 2020/11/05 20:20:23
2020/11/05 20:40:12 2020/11/05 20:20:23
2020/11/05 20:49:53 2020/11/05 20:20:23
2020/11/05 20:56:28 2020/11/05 20:20:23

df2:

time
2020/11/05 20:36:23

I want to get df1 row indices (1) time2 > time, 2. time1 should be close (minimum difference).

How to get this.

I can only filter

df1_filter = df1[df1['time1'] < df2['time'], but after this I sruck how to get match the (1) time2 > time, 2. time1 should be close (minimum difference).

Please kindly someone help,


RE: How to get indices of minimum time difference - deanhystad - Nov-10-2020

The first thing you need to do is extract the datetime strings from the lines. Can you do that?

To determine the shortest duration between the two times you need to convert them to something you can subtract. Any units will do, hours, days, seconds, as long as both times are converted to the same time unit. Even a datetime object will work. Can you do this?

The last part is the easiest. Calculate the duration for each line and keep track of the shortest duration.