Skip to content

Instantly share code, notes, and snippets.

@jfburkhart
Created February 19, 2018 23:01
Show Gist options
  • Save jfburkhart/abb032846ea7525bf9c953789f6d0777 to your computer and use it in GitHub Desktop.
Save jfburkhart/abb032846ea7525bf9c953789f6d0777 to your computer and use it in GitHub Desktop.
def closest(val, vallist, index=True):
""" returns the closest value or index to a date in a list
=========== ======================
keyword description
----------- ----------------------
index [True] returns index
=========== ======================
"""
#assert isinstance(date,dt.datetime), "date must be a datetime object"
minval = sorted(vallist, key=lambda d: abs(val - d))[0]
if index is not True:
return minval
else:
if not isinstance(vallist, list):
vallist = list(vallist)
return vallist.index(minval)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment