Writing a function to calculate date based on relativedelta.
How do I make the ‘frequency’ a variable?
e,g, relativedelta(years=5), ability to define frequency: "years", "months", "days" etc..
Tried f-string literal but i think the apostrophe is giving issues.
def date_ago(date, period, frequency):
"""date: "yyyy-mm-dd"
frequency: "years", "months", "weeks", "days"
period: interger
"""
date_ago = datetime.strptime(date, "%Y-%m-%d") - relativedelta(f'{frequency}={period}')
return date_ago.strftime('%Y-%m-%d')
date_ago("2021-03-31", 5, "years")
ANS: ‘2016-03-31’
>Solution :
You’re probably looking to expand the keyword arguments, not make one string argument!
https://docs.python.org/3/tutorial/controlflow.html#unpacking-argument-lists
relativedelta(**{frequency: period})