I am trying to get the closest date (in a range of dates) to any given date. I tried to use the answer provided in this post - Find the closest date to a given date
It doesn't seem to work for my particular issue though. How could I compare one date to multiple dates and retrieve the date that is closest to the original given date from the range of dates? If you could give me some assistance I'd really appreciate it.
import yfinance as yf
import pandas as pd
import datetime
import time
from datetime import datetime
from datetime import timedelta, date
#Code to retrieve given date
EndDate = date.today() + timedelta(days=90)
Original_Date = str(EndDate.strftime("%Y%m%d"))
#Code to retrieve range of dates
ticker = yf.Ticker("MSFT")
Range_Of_Dates = ticker.options
#Code to retrieve nearest date to give date
def nearest(Range_Of_Dates, Original_Date):
return min(Range_Of_Dates, key=lambda x: abs(x - Original_Date))
nearest_date = nearest(Range_Of_Dates, Original_Date)
print(nearest_date)
The issue is that I keep receiving this error
TypeError: unsupported operand type(s) for -: 'str' and 'str'