0

I have a timestamp taken from a list, and I need to find a row in pandas dataframe that is closest to the timestamp that I have, even a group of rows is fine for me. Here is the sample dataframe

0 6160 Upper 12-7-2019 12:37:51.123572
1 6162 Upper 12-7-2019 12:39:22.355725
2 6175 Upper 12-7-2019 13:21:15.224157
3 6180 Upper 13-7-2019 06:04:29.157111
4 6263 Upper 13-7-2019 07:37:51.123572

and I have a timestamp datetime.datetime(12,7,2019,16,41,20)

So I need it to catch a row at index 2 in this case.

your help is appreciated. Thanks

Sayandip Dutta
  • 15,602
  • 4
  • 23
  • 52
  • Your datetime object should be datetime.datetime(2019,7,12,16,41,20). The order of the arguments is year, month, day, hour, minute, second. See the [Python documentation](https://docs.python.org/3/library/datetime.html#datetime.datetime). – Jakub Aug 01 '20 at 17:43

2 Answers2

3
import pandas as pd
from datetime import datetime

# Input
ref_time = datetime(2019,7,12,16,41,20)
data = [[6160, 'Upper', '12-7-2019 12:37:51.123572'],
        [6162, 'Upper', '12-7-2019 12:39:22.355725'],
        [6175, 'Upper', '12-7-2019 13:21:15.224157'],
        [6180, 'Upper', '13-7-2019 06:04:29.157111'],
        [6263, 'Upper', '13-7-2019 07:37:51.123572']]

# Convert 2D list to DataFrame object
df = pd.DataFrame(data)

# Convert timestamp strings in column at index 2 to datetime objects
df.iloc[:, 2] = pd.to_datetime(df.iloc[:, 2], format='%d-%m-%Y %H:%M:%S.%f')

# Return row with minimum absolute time difference to reference time
print(df.loc[[(abs(df.iloc[:, 2]-ref_time)).idxmin()]])
Jakub
  • 489
  • 3
  • 13
1

You can do:

import datetime
dt = datetime.datetime(2019, 12, 7,16,41,20)

# d column is the date
minidx = (dt - df['d']).idxmin()

print(df.loc[[minidx]])

   a     b        c                          d
2  2  6175   Upper  2019-12-07 13:21:15.224157
YOLO
  • 20,181
  • 5
  • 20
  • 40