如何在psycopg2中将日期转换为字符串? [英] How to cast date to string in psycopg2?

查看:62
本文介绍了如何在psycopg2中将日期转换为字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我确定它与注册自定义类型转换有关 这里.但是,我不知道该怎么做.

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.

我想做的是这样的:SELECT * FROM table并且其中一列是 date 类型,我希望 psycopg2 将其转换为 Python 字符串而不是日期时间.

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.

推荐答案

我找到了方法:

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)

然后运行:

register_New_Date()

这篇关于如何在psycopg2中将日期转换为字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆