0

Is there any way that I can summarise the following code? The codes after each if-else condition are very similar. The only difference is the argument that is passed to relativedelta.

    def change_datetime_objects(dt_objs=[], resolution="year", frequency=1):
        new_dt_list = []
        if resolution="year":
            for time_obj in dt_objs:
                new_dt_list.append(time_obj + relativedelta(years=frequency))
        elif resolution="month":
            for time_obj in dt_objs:
                new_dt_list.append(time_obj + relativedelta(months=frequency))
        elif resolution="week":
            for time_obj in dt_objs:
                new_dt_list.append(time_obj + relativedelta(weeks=frequency))
        elif resolution="day":
            for time_obj in dt_objs:
                new_dt_list.append(time_obj + relativedelta(days=frequency))
        elif resolution="hour":
            for time_obj in dt_objs:
                new_dt_list.append(time_obj + relativedelta(hours=frequency))
        elif resolution="minute":
            for time_obj in dt_objs:
                new_dt_list.append(time_obj + relativedelta(minutes=frequency))
        elif resolution="second":
            for time_obj in dt_objs:
                new_dt_list.append(time_obj + relativedelta(seconds=frequency))

P.S. I thought maybe eval(), exec() or even decorators can help to create a generic form of new_dt_list.append(time_obj + relativedelta(<>=frequency)) but couldn't figure out how they can help.

amiref
  • 3,181
  • 7
  • 38
  • 62

1 Answers1

0

I found an answer to my question inspired by this post.

So, basically to avoid all the redundancies, the arguments should be made before as a dictionary and passed to the function using ** as a keyword argument.

    def change_datetime_objects(dt_objs=[], resolution="year", frequency=1):
        args = {resolution: frequency}
        new_dt_list = []
        for time_obj in dt_objs:
            new_dt_list.append(time_obj + relativedelta(**args))
amiref
  • 3,181
  • 7
  • 38
  • 62