简体   繁体   中英

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

Try using the "BETWEEN" comparator like so:

c.execute("SELECT * FROM ts2 WHERE created_at BETWEEN %s and %s" % (t1, t2))

It was created for this type of query.

Otherwise I'm not sure why the MySQL engine would through that error. Perhaps try adding single quotes around the date placeholders?

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)

Try Converting to iso format :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM