How to create a string mixing " and ' in python, for making a query on influxdb?

I am trying to write the following string sentence to make a query on influx db:

query=SELECT FIRST("price") ,LAST("price") ,MAX("price") ,MIN("price") ,SUM("amount") FROM "table name" WHERE time >= '2018-05-10T12:02:00Z' AND time <= '2018-06-10T12:03:00Z' GROUP BY time(1h)

However since it mixes " and ' in the same string, I haven't been able to parse correctly in python.

When I try:

query='SELECT FIRST("price") ,LAST("price") ,MAX("price") ,MIN("price") ,SUM("amount") FROM "table name" WHERE time >= '2018-05-10T12:02:00Z' AND time <= '2018-06-10T12:03:00Z' GROUP BY time(1h)'

It says invalid syntax due to ' before the date that closes the string. I also try removing or just putting " instead of ', but it didn't work. Finally I tried something more dirty:

query='SELECT FIRST("price") ,LAST("price") ,MAX("price") ,MIN("price") ,SUM("amount") FROM 'tablename' WHERE time >='+"'2018-05-10T12:02:00Z'"+' AND time <= '+"'2018-06-10T12:03:00Z'"+'GROUP BY time(1h)'

but I got an empty query. I appreciate any help with this, thank you.

Upvotes: 0

Views: 408

Answers (1)

mypetlion
mypetlion

Reputation: 2524

If you want a literal ' in the string, and the string literal uses 's you have to escape the ' with a \. Same goes for ". Use your second example, but put \ in front of all your inner '.

query='SELECT FIRST("price") ,LAST("price") ,MAX("price") ,MIN("price") ,SUM("amount") FROM "table name" WHERE time >= \'2018-05-10T12:02:00Z\' AND time <= \'2018-06-10T12:03:00Z\' GROUP BY time(1h)'

Another way to go, which has the added benefit of making your code more readable, is to use Python's multi-line string syntax which is three single or double quotes.

query='''SELECT FIRST("price") 
               ,LAST("price") 
               ,MAX("price") 
               ,MIN("price") 
               ,SUM("amount") 
          FROM "table name" 
          WHERE time >= '2018-05-10T12:02:00Z' 
          AND time <= '2018-06-10T12:03:00Z' 
          GROUP BY time(1h)'''

Upvotes: 1

Related Questions