Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: not enough arguments for format string - Python SQL connection while using %Y-%m

with engine.connect() as con:

    rs = con.execute("""
                        SELECT  datediff(STR_TO_DATE(CONCAT(year,'-',month,'-',day), '%Y-%m-%d') , current_date()) 
                        from TABLE 
                        WHERE datediff(STR_TO_DATE(CONCAT(year,'-',month,'-',day), '%Y-%m-%d') , current_date()) < 900
                        group by STR_TO_DATE(CONCAT(year,'-',month,'-',day), '%Y-%m-%d');
                    """)

I feel the compiler is getting confused with '%Y-%m-%d', I might be wrong. Could someone help me on how to avoid this error:

Type Error:not enough arguments for format string

like image 626
ForeverLearner Avatar asked Oct 18 '16 20:10

ForeverLearner


People also ask

How do you use %s in Python?

The %s operator is put where the string is to be specified. The number of values you want to append to a string should be equivalent to the number specified in parentheses after the % operator at the end of the string value. The following Python code illustrates the way of performing string formatting.

How do you format a string in Python?

To use formatted string literals, begin a string with f or F before the opening quotation mark or triple quotation mark. Inside this string, you can write a Python expression between { and } characters that can refer to variables or literal values.


2 Answers

It sees your % signs and thinks you want to format the string. I believe you should be able to replace them with %% to indicate that you want the character, not a format substitution.

like image 102
alexbclay Avatar answered Oct 12 '22 22:10

alexbclay


You need to escape the %:

with engine.connect() as con:

    rs = con.execute("""
                        SELECT  datediff(STR_TO_DATE(CONCAT(year,'-',month,'-',day), '%%Y-%%m-%%d') , current_date()) 
                        from TABLE 
                        WHERE datediff(STR_TO_DATE(CONCAT(year,'-',month,'-',day), '%%Y-%%m-%%d') , current_date()) < 900
                        group by STR_TO_DATE(CONCAT(year,'-',month,'-',day), '%%Y-%%m-%%d');
                    """)

% is a reserved character in MySQL (wildcard).

like image 38
Eugene Avatar answered Oct 12 '22 22:10

Eugene