0

I'm using the following method to create the object stated in the title:

from dateutil import relativedelta

MA_dict = {'years': 0,
         'months': 0,
         'weeks': 0,
         'days': 1,
         'hours': 0,
         'minutes': 0,
         'seconds': 0}


def dict2relativedelta(dict):
    '''
    creates relativedelta variable that can be used to calculate dates
    '''
    dt = relativedelta.relativedelta(years=dict['years'], months=dict['months'], weeks=dict['weeks'], days=dict['days'],
                                     hours=dict['hours'], minutes=dict['minutes'], seconds=dict['seconds'])
    return dt

However, I would like to simplify this so that I can just pass

MA_dict = {'days': 1}

and the function will return the same. How can I do that?

cheesus
  • 1,111
  • 1
  • 16
  • 44
  • Can you please explain your question? I'm unable to get what you want. – Avi Nov 07 '19 at 13:04
  • in essence i want a customer to just pass me a dictionary in the shape of MA_dict = {'days': 1} or MA_dict = {'days': 7} or MA_dict = {'seconds': 7}, that I can autopmatically bring into this relativedelta format, which I can then just add to a timestamp :) – cheesus Nov 07 '19 at 16:08

1 Answers1

1

You don't need a special function for this as Python has argument unpacking with the ** operator. You can accomplish what you want with:

MA_dict = {"days": 1}
rd = relativedelta.relativedelta(**MA_dict)
Paul
  • 10,381
  • 13
  • 48
  • 86
  • TypeError: 'module' object is not callable – cheesus Nov 08 '19 at 11:07
  • 1
    I wrote my answer assuming you imported the relativedelta class from the relativedelta module. I've adjusted it. – Paul Nov 09 '19 at 03:45
  • very smooth solution, thanks. FYI there is a small syntax error at the last bracket which I couldn't edit out since "Edits must be at least 6 characters" :D – cheesus Nov 11 '19 at 09:23