问题
I'm sure it has something to do with registering custom type cast as described here. However, I'm not sure how to do that.
What I want to do is something like this:
SELECT * FROM table
and where a column is of date
type, I want psycopg2 to convert it to Python string instead of datetime.
回答1:
I found how to do it:
def register_New_Date():
# Cast PostgreSQL Date as Python string
# Reference:
# 1. http://initd.org/psycopg/docs/extensions.html#psycopg2.extensions.new_type
# 2. http://initd.org/psycopg/docs/advanced.html#type-casting-from-sql-to-python
# 1082 is OID for DATE type.
NewDate = psycopg2.extensions.new_type((1082,), 'DATE', psycopg2.STRING)
psycopg2.extensions.register_type(NewDate)
Then run:
register_New_Date()
来源:https://stackoverflow.com/questions/32184465/how-to-cast-date-to-string-in-psycopg2