Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format timedelta using string variable

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)
like image 593
sdot257 Avatar asked Feb 25 '14 03:02

sdot257


People also ask

How do you convert a string to a Timedelta?

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.

How do I convert a string to a datetime Timedelta in Python?

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.

What is the use of Timedelta () function?

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.

How do I convert a date to a string in Python?

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.


1 Answers

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)
like image 176
falsetru Avatar answered Nov 14 '22 23:11

falsetru