简体   繁体   中英

how to pass string into a method as a keyword argument

Is it possible to pass a string as a keyword argument into a function/method?

the code below works just fine

start_time = datetime.datetime.strptime('2019-01-01', '%Y-%m-%d')
end_time = start_time + datetime.timedelta(days=1)
print(end_time)

However, if I will pass a string into datetime.timedelta

delta = 'days=1'
start_time = datetime.datetime.strptime('2019-01-01', '%Y-%m-%d')
end_time = start_time + datetime.timedelta(delta)
print(end_time)

then it will return

TypeError: unsupported type for timedelta days component: str

But what if I get this "days=1" or "hours=2", or "seconds=5" from user input?

One way to make that work is to parse user input and create multiple if/elif statements.

Is there anything better?

Perhaps pass in the named parameters using the ** operator:

params=dict()
params['hours']=2
datetime.timedelta(**params)
# datetime.timedelta(0, 7200)

No, because a keyword argument is syntax , not data. The following is legal, though:

end_time = start_time + datetime.timedelta(**dict([delta.split("=")]))

This

  1. Splits "days=1" into ["days", "1"]
  2. Creates a dict {"days": "1"}
  3. Uses the dict as a source of keyword arguments for timedelta

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM