Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select DateTime mysql query in python

I have the following table in my MySQL database:

id teplota created_at
1 12.521 2017-02-01 17:49:53
1 12.852 2017-02-02 17:50:53
1 12.852 2017-02-03 17:50:53
... ... ...

Column created_at has type timestamp, here is the column definition in my CREATE TABLE statement:

created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP

When I use this select command in DB it normally works and I get correct output

select * from ts2 where created_at >= "2017-02-01" and created_at < "2017-02-02"

But I have a problem if I want use it in my python code:

import datetime

t1 = datetime.datetime(2017, 2, 1)
t2 = datetime.datetime(2017, 2, 2)
t1 = str(t1)
t2 = str(t2)
c.execute("select * from ts2 where created_at >= %s and created_at < %s;" % (t1, t2)) 

I get the following error:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '00:00:00 and created_at < 2017-01-31 00:00:00' at line 1

Any idea what I might be doing wrong? Thanks

like image 268
Luboss Avatar asked Apr 21 '26 02:04

Luboss


1 Answers

I had the same problem and used ' around %s to solve it:

sql_query = "select * from ts2 where created_at >= '%s' and created_at < '%s';" % (t1, t2)
c.execute(sql_query)
like image 71
Guilherme Avatar answered Apr 22 '26 17:04

Guilherme



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!