Dynamic Variable Parameter Python

Question:

I feel like this isn’t possible but I thought I would ask anyway. I have a short piece of code that I’m intending to use to add weeks/months/year to a given date. The time frame chosen will be dependent on a string passed. My question is when it comes to something like relativedelta is it possible to dynamically choose with parameter to use? So if the string passed is "weeks" then it would pass relativedelta(weeks=1) and if "months" it would pass relativedelta(months=1)? I’ve attached my code which I know doesn’t work but it’s just to illustrate what I’m imagining.

from datetime import datetime, timedelta
from dateutil.relativedelta import relativedelta

today = datetime.today()

print(today)
print(today + relativedelta(months=2))

loop = 1
for i in range(5):
    variable_weeks = 'weeks'
    next_month = today + relativedelta(variable_weeks=loop)
    date_string = next_month.strftime('%Y-%m-%d')
    print(date_string)
    loop += 1
Asked By: MitchW

||

Answers:

You can do:

...
variable_weeks = 'weeks'
next_month = today + relativedelta(**{variable_weeks: loop})
...

This uses a dict for the key-value pairs that you can define with variables. The dict is then unpacked as the input for relativedelta.

Answered By: MangoNrFive
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.