Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to raw query with datetime in SqlAlchemy Python3

So I am trying to query from a table messages on the basis of a datetime field timeStamp but I keep getting an error. Maybe the way I am trying to query is not correct.

def get_test(self, start_date, end_date):
        
        query = 'SELECT * from messages WHERE messages."timeStamp" > {start_date} and messages."timeStamp" < {end_date};'
        res = self.session.execute(query)
        self.session.commit()
        
        return res.fetchall()

When I run this code, I get the following error.

sqlalchemy.exc.ProgrammingError: (psycopg2.errors.SyntaxError) syntax error at or near "00"
LINE 1: ... messages WHERE messages."timeStamp" > 2021-06-01 00:00:00 a...

I also tried using datetime.strptime method but that didn’t work too.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

def get_test(self, start_date, end_date):
        
        query = f'''SELECT * from messages WHERE messages."timeStamp" > {datetime.strptime(start_date, "%Y-%m-%d %H:%M:%S")}   
        and messages."timeStamp" < {datetime.strptime(end_date, "%Y-%m-%d %H:%M:%S")};'''
        res = self.session.execute(query)
        self.session.commit()
        
        return res.fetchall()

I also tried using the query parameters but that didn’t work either.

 def get_test(self, start_date, end_date):
        
        query = f'SELECT * from messages WHERE messages."timeStamp" > %s and messages."timeStamp" < %s;'
        res = self.session.execute(query, (datetime.strptime(start_date, "%Y-%m-%d %H:%M:%S"), 
                                           datetime.strptime(end_date, "%Y-%m-%d %H:%M:%S")))
        self.session.commit()
        
        return res.fetchall()

Would really appreciate if anyone could help me out here.

>Solution :

I think there are a couple of things going on here.

I don’t think your f-strings are populating and strptime is for turning strings into dates, not the other way round.

I’d write it like this:

query = f'SELECT * from messages WHERE messages."timeStamp" > {start_date.isoformat()} and messages."timeStamp" < {end_date.isoformat()};'
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading