How to cast date to string in psycopg2?

落花浮王杯 提交于 2019-12-13 02:26:13

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!