Using Python 2.6
Given the following line of code, how can I dynamically build the value for timedelta from variables in a DB?
next_alert_date = datetime.strptime(start_due_date, '%Y-%m-%d') + timedelta(days=2)
Basically, I need something like this but it doesnt appear to work.
SyntaxError: invalid syntax
next_alert_date = datetime.strptime(start_due_date, '%Y-%m-%d') + timedelta(%s=%d) % (interval_type, interval_num)
Convert String to TimeDelta We can even convert time in string format to datetime by using the strptime() function and then extracting the timedelta information using the timedelta module. We can use the repr(td) to print the timedelta as a constructor with attributes in a string format.
Method 1: Program to convert string to DateTime using datetime. strptime() function. strptime() is available in DateTime and time modules and is used for Date-Time Conversion. This function changes the given string of datetime into the desired format.
timedelta() function. Python timedelta() function is present under datetime library which is generally used for calculating differences in dates and also can be used for date manipulations in Python. It is one of the easiest ways to perform date manipulations.
To convert Python datetime to string, use the strftime() function. The strftime() method is a built-in Python method that returns the string representing date and time using date, time, or datetime object.
Maybe you're misunderstanding %
operator used for string formatting operation; it is used to make a string.
>>> 'timedelta(%s=%d)' % ('days', 2)
'timedelta(days=2)'
Use **
operator to pass keyword arguments dynamically:
>>> datetime.timedelta(**{'days': 2})
datetime.timedelta(2)
>>> interval_type = 'days'
>>> interval_num = 2
>>> datetime.timedelta(**{interval_type: interval_num})
datetime.timedelta(2)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With