I have a Pandas dataframe which is indexed by a DatetimeIndex:
DatetimeIndex: 53732 entries, 1993-01-07 12:23:5
I was confronting the same problem today. I wanted a function able to give me the closest value prior a given timestamp. Here is the function I got:
def get_nearest_past(data, timestamp):
index = data.index.get_loc(timestamp,"ffill")
return data.iloc[index]
In the case that you need the global closest (and not the closest before as in my case), you can use:
def get_nearest(data, timestamp):
index = data.index.get_loc(timestamp,"nearest")
return data.iloc[index]
You can find more information in the get_loc documentation.