Getting the closest date to a given date

前端 未结 8 618
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:12

    decorate, filter, find the closest date, undecorate

    >>> base_date = "10/29 06:58 AM"
    >>> list_date = [
    ...     ('10/30 02:18 PM', '-103', '-107'),
    ...     ('10/30 02:17 PM', '+100', '-110'),
    ...     ('10/29 02:15 AM', '-101', '-109')
    ... ]
    >>> import datetime
    >>> fmt = '%m/%d %H:%M %p'
    >>> base_d = datetime.datetime.strptime(base_date, fmt)
    >>> candidates = ((datetime.datetime.strptime(d, fmt), d, x, y) for d, x, y in list_date)
    >>> candidates = min((dt, d, x, y) for dt, d, x, y in candidates if dt > base_d)
    >>> print candidates[1:]
    ('10/30 02:17 PM', '+100', '-110')
    

提交回复
热议问题