Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

retrieve INTERVAL columns as ISO 8601 string #449

Closed
flokli opened this issue Jun 30, 2016 · 2 comments
Closed

retrieve INTERVAL columns as ISO 8601 string #449

flokli opened this issue Jun 30, 2016 · 2 comments

Comments

@flokli
Copy link

flokli commented Jun 30, 2016

Hey,

PostgreSQL stores INTERVAL columns with separate years and months, however, psycopg2 converts these to days, as Python's timedelta doesn't support years and months.

However, sometimes it might be desirable to get the months and years originally stored in the PostgreSQL column, as the length of a months and year depends on the start date. psycopg2 should also provide an interface to simply return the column value as a string in iso_8601 output style, instead of converting to timedelta, so it can be further processed by packages like isodate.

@dvarrazzo
Copy link
Member

You can do that registering your own adapter. More specifically you can register the string adapter on the timedelta type.

>>> psycopg2.extensions.register_type(
    psycopg2.extensions.new_type(
        psycopg2.extensions.INTERVAL.values, 'INTERVAL_STR', psycopg2.STRING),
    cur)

>>> cur.execute("select '1 month'::interval")
>>> cur.fetchone()[0]
'1 mon'

>>> cur.execute("set intervalstyle = 'iso_8601'")
>>> cur.execute("select '1 month'::interval")
>>> cur.fetchone()[0]
'P1M'

@flokli
Copy link
Author

flokli commented Jul 4, 2016

Awesome, thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants