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.