Variables within a function

Viewed 35

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'

1 Answers
Related