1

I am using the the following sql in MySQL terminal and it works fine.

select * from metric_measured_value where metric_id=18 and measurement_time>(now()-INTERVAL 2 year);

However, when I used it in python code, it won't work.

res = self._db.Query("""SELECT * FROM metric_measured_value
                                            WHERE metric_id = %s
                                            AND measurement_time>(now()-%s)""",
                                            (metric_id, max_interval))

Here metric_id=18 and max_interval="INTERVAL 2 year"

The error message is: Truncated incorrect DOUBLE value: 'INTERVAL 2 year'

What am I doing wrong?

Thanks for you help.

2 Answers 2

2

This is probably your DB access library utilizes prepared statements. INTERVAL is a MySQL keyword and it is not expected to be passed into prepared statements.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. That's the problem. Is there a way to avoid this?
What Adam suggests is probably the best way.
2

Instead of calculating the interval on the database, why not do it in python, and pass it into your measurement time.

from datetime import date
max_interval = 2
today = date.today()
interval = date.today()
interval = interval.replace(year=interval.year - max_interval)
delta = today - interval

res = self._db.Query("""SELECT * FROM metric_measured_value
                                            WHERE metric_id = %s
                                            AND measurement_time > %s""",
                                            (metric_id, delta.days))

Just saw this question on gmail style date formating, which suggested a relative dates module. It's more relative to now, but it might give some ideas.

3 Comments

Thanks for the answer. It's a good idea, but here the interval is not necessarily year, it might be minute, hour, day, month, week or year. Is there a way to easily do this?
If you know the type, you can write a switch statement. Then, use datetime.date to calculate difference in days, weeks, months, years, and datetime.datetime to calculate the difference in seconds, minutes and hours.
Yes, I guess that's the best option I should try. Thanks Adam.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.