0

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
1
  • The arguments to relativedelta are keyword arguments so you can construct a dict of arguments e.g. d={"weeks":2} or d={"years":3, "days":2} and then call relativedelta(**d) Commented Jul 30, 2022 at 22:59

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.