find_closest_date¶
- pyhelpers.ops.find_closest_date(date, lookup_dates, as_datetime=False, fmt='%Y-%m-%d %H:%M:%S.%f')[source]¶
Finds the closest date to a given date from a list of dates.
- Parameters:
date (str | datetime.datetime) – Date to find the closest match for.
lookup_dates (Iterable) – Iterable of dates to search within.
as_datetime (bool) – Whether to return the closest date as a datetime.datetime object; defaults to
False
which returns a string representation.fmt (str) – Format string for datetime parsing and formatting; defaults to
'%Y-%m-%d %H:%M:%S.%f'
.
- Returns:
Closest date to the given date.
- Return type:
str | datetime.datetime
Examples:
>>> from pyhelpers.ops import find_closest_date >>> import pandas >>> lookup_dates = pandas.date_range('2019-01-02', '2019-12-31') >>> lookup_dates DatetimeIndex(['2019-01-02', '2019-01-03', '2019-01-04', '2019-01-05', '2019-01-06', '2019-01-07', '2019-01-08', '2019-01-09', '2019-01-10', '2019-01-11', ... '2019-12-22', '2019-12-23', '2019-12-24', '2019-12-25', '2019-12-26', '2019-12-27', '2019-12-28', '2019-12-29', '2019-12-30', '2019-12-31'], dtype='datetime64[ns]', length=364, freq='D') >>> date = '2019-01-01' >>> closest_example_date = find_closest_date(date, lookup_dates) >>> closest_example_date '2019-01-02 00:00:00.000000' >>> date = pandas.to_datetime('2019-01-01') >>> closest_date = find_closest_date(date, lookup_dates, as_datetime=True) >>> closest_date Timestamp('2019-01-02 00:00:00', freq='D')