2 回答
TA贡献1851条经验 获得超5个赞
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()]])
TA贡献1808条经验 获得超4个赞
你可以做:
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
添加回答
举报