Skip to content

Forcing a max year instead of throwing ValueError #1614

Closed Answered by dvarrazzo
ying-w asked this question in Q&A
Discussion options

You must be logged in to vote

If you can make a comparison in postgres you may as well sanitize the value returning them within an expected range:

SELECT ... min(date_field, '9999-12-31'::date) AS date_field ...

If you want to use a custom adapter, you can make one that returns datetime.max in case of overflow. The example is for the timestamptz; you can do something similar for timestamp and date types.

import datetime as dt
import psycopg2
from psycopg2.extensions import PYDATETIMETZ, PYDATETIME, PYDATE

def cast_safe_tstz(data, cur):
    try:
        return PYDATETIMETZ(data, cur)
    except ValueError:
        return dt.datetime.max

SAFE_TSTZ = psycopg2.extensions.new_type(PYDATETIMETZ.values, "SAFE_TSTZ", cast_…

Replies: 2 comments 1 reply

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
1 reply
@dvarrazzo
Comment options

Answer selected by ying-w
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants