Logic here use a merge_asof , we need to adjust it due to , merge_asof will use the 2nd dataframe mutiple times , then we need additional key here is datetime to drop a duplicate
masterdf.index=pd.to_datetime(masterdf.index)
masterdf=masterdf.sort_index().reset_index()
slavedf.index=pd.to_datetime(slavedf.index)
slavedf=slavedf.sort_index().reset_index()
slavedf['datetime2']=slavedf['datetime']
slavedf['key']=slavedf.index
newdf=pd.merge_asof(masterdf,slavedf,on='datetime',tolerance=pd.Timedelta('60s'),direction='nearest')
newdf['diff']=(newdf.datetime-newdf.datetime2).abs()
newdf=newdf.sort_values('diff').drop_duplicates('key')
newdf
Out[35]:
datetime AA BB datetime2 diff
2 2019-10-01 07:53:54 77.425134 60 2019-10-01 07:53:54 00:00:00
1 2019-10-01 07:53:01 77.491655 50 2019-10-01 07:53:00 00:00:01
If you are a beginner and want to know more about Data Science the do check out the Data Science course