find_closest_date
- pyhelpers.ops.find_closest_date(date, lookup_dates, as_datetime=False, fmt='%Y-%m-%d %H:%M:%S.%f')
Find the closest date of a given one from a list of dates.
- Parameters:
date (str or datetime.datetime) – a date
lookup_dates (Iterable) – an array of dates
as_datetime (bool) – whether to return a datetime.datetime-formatted date, defaults to
False
fmt (str) – datetime format, defaults to
'%Y-%m-%d %H:%M:%S.%f'
- Returns:
the date that is closest to the given
date
- Return type:
str or datetime.datetime
Examples:
>>> from pyhelpers.ops import find_closest_date >>> import pandas >>> example_dates = pandas.date_range('2019-01-02', '2019-12-31') >>> example_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') >>> example_date = '2019-01-01' >>> closest_example_date = find_closest_date(example_date, example_dates) >>> closest_example_date '2019-01-02 00:00:00.000000' >>> example_date = pandas.to_datetime('2019-01-01') >>> closest_example_date = find_closest_date(example_date, example_dates, as_datetime=True) >>> closest_example_date Timestamp('2019-01-02 00:00:00', freq='D')