Skip to content

Instantly share code, notes, and snippets.

@mumbleskates
Last active April 7, 2016 19:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mumbleskates/c71496555365f0ff3ed5c3061a6d777f to your computer and use it in GitHub Desktop.
Save mumbleskates/c71496555365f0ff3ed5c3061a6d777f to your computer and use it in GitHub Desktop.
Find the closest date to another date from some inputs
# coding=utf-8
from __future__ import unicode_literals
from datetime import datetime
DATE_FORMAT = "%m/%d"
def convert_date(date_str):
return datetime.strptime(date_str, DATE_FORMAT)
def get_closest_date(target, others):
"""
Accept a date and an iterable of dates and return the date from the iterable that is closest to the target.
All date values are strings in mm/dd format. February 29th does not exist. If two dates are equally close
to the target, the earlier one is returned.
"""
target = convert_date(target)
_, closest = min((abs(target - x), x) for x in map(convert_date, others))
return closest.strftime(DATE_FORMAT)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment