Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Variables within a function

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’

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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})
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading