1

I am working on a Flask project with Postgresql as my database. I have a schema called interest which looks like

create table interest(
usr int,
activity_category int,
activity_subcategory int, 
pid int,
start_time timestamp,
end_time timestamp,
budget int check (budget >= 0),
primary key (usr, activity_category, activity_subcategory, pid, start_time, end_time),
foreign key (usr) references users(userid),
foreign key(pid, activity_category, activity_subcategory) references location(pid, aid, aaid)

);

I am trying to insert values into the interest table. At present, I have starttime and endtime as strings but I guess I need to somehow typecast them to timestamp. I have tried these two methods but none of them work.

entry_by_location = g.conn.execute("insert into interest(usr, activity_category, activity_subcategory, pid, start_time, end_time, budget) values (%d, %d, %d, %d, to_timestamp(%s::text, 'YYYY-MM-DD HH:MI'), to_timestamp(%s::text, 'YYYY-MM-DD HH:MI'), %d)" %(int(uid), int(aaid), int(aid), int(pid), starttime, endtime, budget))

and

entry_by_location = g.conn.execute("insert into interest(usr, activity_category, activity_subcategory, pid, start_time, end_time, budget) values (%d, %d, %d, %d, %s::timestamp, %s::timestamp, %d)" %(int(uid), int(aaid), int(aid), int(pid), starttime, endtime, budget))

The error that I get is -

ProgrammingError: (psycopg2.ProgrammingError) syntax error at or near "10" LINE 1: ... end_time, budget) values (1, 2, 7, 1, 2016-11-15 10:13::tim... ^ [SQL: 'insert into interest(usr, activity_category, activity_subcategory, pid, start_time, end_time, budget) values (1, 2, 7, 1, 2016-11-15 10:13::timestamp, 2016-10-15 11:24::timestamp, 1000)']

I've spent two days trying to figure this out. Any sort of help would be really appreciated.

Thank you!

5
  • 1
    Trying adding quotes like '%s' Commented Nov 9, 2016 at 7:01
  • That worked! Wow. This is interesting. I need to put quotes with %s so that a date with a string data type gets converted to '2014-20-10' instead of simply being 2014-20-10. Commented Nov 9, 2016 at 7:14
  • Thank a lot @viki888 Commented Nov 9, 2016 at 7:17
  • I will post this solution as an answer and kindly make it as the best answer, so that it would be helpful for others Commented Nov 9, 2016 at 7:19
  • Sounds good! Will do. Commented Nov 9, 2016 at 7:24

1 Answer 1

2

In the error message it is clear that, there is an error near 10. That is the sql cannot recognise the datatype of 2016-11-15 10:13 due to space exist between Date and Time.

So adding quotes to %s will solve the issue like '%s'.

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

Comments

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.