Getting the closest date to a given date

前端 未结 8 611
Happy的楠姐
Happy的楠姐 2020-12-03 08:50

Given this base date:

base_date = \"10/29 06:58 AM\"

I want to find a tuple within the list that contains the closest date to the bas

8条回答
  •  抹茶落季
    2020-12-03 09:05

    I was looking up this problem and found some answers, most of which check all elements. I have my dates sorted (and assume most people do), so if you do as well, use numpy:

    import numpy as np
    // dates is a numpy array of np.datetime64 objects
    dates = np.array([date1, date2, date3, ...], dtype=np.datetime64)
    timestamp = np.datetime64('Your date')
    np.searchsorted(dates, timestamp)
    

    searchsorted uses binary search, which uses the fact the dates are sorted, and is thus very efficient. If you use pandas, this is possible:

    dates = df.index # df is a DatetimeIndex-ed dataframe
    timestamp = pd.to_datetime('your date here', format='its format')
    np.searchsorted(dates, timestamp)
    

    The function returns the index of the closest date (if the searched date is included in dates, its index is returned [if that isn't wanted, use side='right' as an argument into the function]), so to get the date do this:

    dates[np.searchsorted(dates, timestamp)]
    

提交回复
热议问题