Using infinite values with DateTimeTZRange

From: "Fennell, Felix W(dot)" <felnne(at)bas(dot)ac(dot)uk>
To: "psycopg(at)postgresql(dot)org" <psycopg(at)postgresql(dot)org>
Subject: Using infinite values with DateTimeTZRange
Date: 2017-08-20 14:23:52
Message-ID: 0A966393-5548-45AF-B0BC-4FE1D658849D@bas.ac.uk
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: psycopg

Hi,

Apologies if this isn’t the right place to ask questions like this but I am having difficulty storing ‘infinite’ dates using the DateTimeTZRange object.

I have a Postgres database with a ‘tstzrange’ column (named validity) and I’d like to store a value in this similar to ‘[“2010-01-01 10:00:00 +01”, infinity]’.

I’m using SQL Alchemy’s ORM to store data from Python with a model containing:

```
from sqlalchemy.dialects.postgresql import TSTZRANGE
...

class Principle(Base):
__tablename__ = 'principles'

id = Column(Integer, primary_key=True)
validity = Column(TSTZRANGE())
```

And then code to generate a timestamp range, using ‘datetime.max()’ to represent infinity as mentioned here [1]:

```
from psycopg2.extras import DateTimeTZRange
...

from_now = timezone("utc").localize(datetime.now())
until_forever = timezone("utc").localize(datetime.max)

validity = DateTimeTZRange(from_now, until_forever)
```

I then added the code from [2] to translate the use of datetime.max into 'infinity' for use in Postgres, however when I
tried to save this model I got this error instead:

'argument 1 must be datetime.date, not DateTimeTZRange'

I naively tried changing this line:

```
psycopg2.extensions.register_adapter(datetime.date, InfDateAdapter)
```

to:

```
psycopg2.extensions.register_adapter(DateTimeTZRange, InfDateAdapter)
```

But that gave me the same error. I'm afraid I don't know Python or this library well enough to adapt the snippet from
[2] into a form that will work with timestamp ranges - assuming that's what I need to do?

Does anyone here from any advice for how to make this work? I did try googling, but I kept getting directed back to [2].

Thanks,
Felix.

[1] http://initd.org/psycopg/docs/extras.html#range-data-types
[2] http://initd.org/psycopg/docs/usage.html#infinite-dates-handling

________________________________
This message (and any attachments) is for the recipient only. NERC is subject to the Freedom of Information Act 2000 and the contents of this email and any reply you make may be disclosed by NERC unless it is exempt from release under the Act. Any material supplied to NERC may be stored in an electronic records management system.
________________________________

Responses

Browse psycopg by date

  From Date Subject
Next Message Daniele Varrazzo 2017-08-21 12:14:22 Re: Using infinite values with DateTimeTZRange
Previous Message Pavel Raiskup 2017-08-17 12:25:41 Re: documentation build failure with python sphinx 1.6.3