对于像2020-10-26T14:33:00这样的Python字符串值,有没有一种方法可以在执行插入到数据库的psycopg2查询之前测试Postgresql是否接受它?
发布于 2020-11-28 23:29:17
在处理Python中的日期(时间)时,我发现dateutil模块是非常有价值的。使用它的parse部分将捕获大多数格式错误的时间戳字符串,并将不正确的时间戳字符串转换为psycopg2可以使用的日期时间。
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:00https://stackoverflow.com/questions/65050830
复制相似问题