Search code examples
pythonpython-2.7python-datetime

Pass time unit as a variable to the keyword argument in time delta function.


Is it possible to achieve something like this?

def subtract_from_date(date, time_unit, num):
    return date - timedelta(time_unit=num)

Basically I am feeling too lazy to put if elif conditions for various input time units like minutes, hours, weeks, days etc.


Solution

  • You can use a dictionary and apply it as a mapping argument:

    timedelta(**{time_unit: num})
    

    Demo:

    >>> from datetime import datetime, timedelta, date
    >>> def subtract_from_date(date, time_unit, num):
    ...     return date - timedelta(**{time_unit: num})
    ... 
    >>> subtract_from_date(date.today(), 'days', 5)
    datetime.date(2015, 3, 21)