Use variables as keywords for functions with pre-defined keywords (Python)
<p>I'm trying to create a simple function that allows a user to input basic information that will change the values of a datetime object, and I'd like to find a way to make it as clean as possible by using a variable as a keyword.  This can easily be done a different way, but I figured it'd be useful to know how to replace pre-set keywords.</p>

<p>The datetime object has a .replace() method that takes any time value as a keyword:</p>

<blockquote>
  <p>datetime.replace([year[, month[, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]]]]])</p>
</blockquote>

<p>But I want to allow the user to specify how much of which kind of time (e.g., 2 days; 4 hours; 1 month).</p>

<p>I'm trying to replace any of the above keywords up to "minute" with whatever the user inputs, which is stored in the <em>time_type</em> variable, but I get "<strong>TypeError: 'time_type' is an invalid keyword argument for this function</strong>".</p>

<pre><code>    start_time = datetime.datetime(2016, 09, 16, 15, 30)

    def change_time(integer, time_string):
        time_type = time_string.replace("s","")  # de-pluralizes input
        new_time = getattr(start_time, time_type) + integer
        print(start_time.replace(time_type=new_time))

    change_time(2, "days")
</code></pre>

<p>This should print the new start_time, which is (2016, 09, 18, 15, 30), but I just get an error.</p>

<p>Change your last line to something like this:</p>

<pre><code>year = start_time.year
month = start_time.month
day = start_time.day
hour = start_time.hour
minute = start_time.minute
second = start_time.second
microsecond = start_time.microsecond
exec(time_type + '='+str(new_time))
print(start_time.replace(year, month, day, hour, minute, second, microsecond)
</code></pre>

python datetime