IndiaSke
IndiaSke

Reputation: 358

Python3 psycopg2 test timestamp value before query

With a Python string value like 2020-10-26T14:33:00, is there a way to test if Postgresql will accept it before doing a psycopg2 query to insert in DB ?

Upvotes: 1

Views: 311

Answers (1)

Adrian Klaver
Adrian Klaver

Reputation: 19570

When dealing with date(time)s in Python I have found the dateutil module invaluable. Using the parse portion of it will catch most malformed timestamp strings and will convert those that aren't into a datetime that psycopg2 can use.:

from dateutil.parser import parse
parse('33/9/2020')
ParserError: day is out of range for month: 33/9/2020

parse('26/10/2020 14:33')
Out[4]: datetime.datetime(2020, 10, 26, 14, 33)

import psycopg2
con = psycopg2.connect("dbname=test host=localhost user=postgres")
cur = con.cursor()
cur.execute("insert into dt_test values(%s, %s)", (8, parse('26/10/2020 14:33')))
con.commit()

select * from dt_test;

 id |       ts_fld        
----+---------------------
  8 | 10/26/2020 14:33:00

Upvotes: 2

Related Questions