Find the closest date to a given date
This function will return the datetime
in items
which is the closest to the date pivot
.
def nearest(items, pivot):
return min(items, key=lambda x: abs(x - pivot))
The good part this function works on types other than datetime
too out of the box, if the type supports comparison, subtraction and abs
, e.g.: numbers and vector types.
As answered on this link link, 'truncate' function is there for you.
df.truncate(before='2012-01-07')
Or you can use get_loc with 'nearest', 'backfill' or 'ffill' option.
df.iloc[df.index.get_loc(datetime.datetime(2016,2,2),method='nearest')]