Last active
April 7, 2016 19:08
-
-
Save mumbleskates/c71496555365f0ff3ed5c3061a6d777f to your computer and use it in GitHub Desktop.
Find the closest date to another date from some inputs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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