Davi A. Sampaio
Davi A. Sampaio

Reputation: 355

How to convert a string into a parameter of a function?

I have to subtract 2 dates using datetime like this:

datetime.datetime.now() - datetime.timedelta(minutes=15)
# subtracting 15 minutes

The problem is that i don't necessarily need to subtract minutes. I have a dictionary that tells what i should subtract.

period = {'quantity': '15', 'time': 'minutes'}

But i need that when the dictionary changes, the subtracted time also changes. Like this:

if period['time'] == 'minutes':
    tempo_atras = datetime.datetime.now() -datetime.timedelta(minutes=int(period['quantity']))
elif period['time'] == 'hours':
    tempo_atras = datetime.datetime.now() - datetime.timedelta(hours=int(period['quantity']))
elif period['time'] == 'days':
    tempo_atras = datetime.datetime.now() - datetime.timedelta(days=int(period['quantity']))
elif period['time'] == 'weeks':
    tempo_atras = datetime.datetime.now() - datetime.timedelta(weeks=int(period['quantity']))

I feel that the way i wrote it is not clean, so i need a way to convert the period['time'] string in the function parameter; something like:

tempo_atras = datetime.datetime.now() - datetime.timedelta(period['time']=int(period['quantity']))

How can i do this?

Upvotes: 2

Views: 263

Answers (2)

wjandrea
wjandrea

Reputation: 33179

You can use the dictionary unpacking operator ** to expand a dict into keyword arguments, so you just need to make the dict first.

q = {period['time']: int(period['quantity'])}
tempo_atras = datetime.datetime.now() - datetime.timedelta(**q)

Docs:

Upvotes: 3

Mohammad
Mohammad

Reputation: 3396

You have to convert the dictionary so that the period is pointing to the quantity. Then use dictionary unpacking normally.

import datetime
period = {'quantity': '15', 'time': 'minutes'}
# convert the dictionary to a dictionary of "minutes"= "15"
period = {period['time']: int(period['quantity'])}
print(period)
tempo_atras = datetime.datetime.now() - datetime.timedelta(**period)

Note: you can read more about this format (and the * format for lists) here: More on Defining Functions

Upvotes: 2

Related Questions