Here's my reworking of the example for time types:

"""
from datetime import datetime, timedelta, date
from sqlalchemy import MetaData, Table, Column, DateTime, Date,
Interval
from sqlalchemy.orm import mapper, create_session

metadata = MetaData('postgresql:///avdd')

interval_table1 = Table('period1', metadata,
    Column('start', DateTime, primary_key=True),
    Column('end', DateTime, primary_key=True))

interval_table2 = Table('period2', metadata,
    Column('start', DateTime, primary_key=True),
    Column('length', Interval, primary_key=True))

metadata.create_all()

class BasePeriod(object):
    @hybrid
    def contains(self, instant):
        return (self.start <= instant) & (instant < self.end)

    @hybrid
    def intersects(self, other):
        return (self.start < other.end) & (self.end > other.start)

    def __repr__(self):
        return "%s(%s..%s)" % (self.__class__.__name__, self.start,
self.end)

class Period1(BasePeriod):
    length = hybrid_property(lambda s: s.end - s.start)
    def __init__(self, start, end):
        self.start = start
        self.end = end

mapper(Period1, interval_table1)

class Period2(BasePeriod):
    end = hybrid_property(lambda s: s.start + s.length)
    def __init__(self, start, length):
        self.start = start
        self.length = length

mapper(Period2, interval_table2)

session = create_session()

intervals = [timedelta(seconds=1),
             timedelta(1),
             timedelta(366)]

instants = [datetime.now(),
            datetime(2000, 1, 2, 3, 4, 5),
            datetime(1987, 6, 5, 4, 3, 2, 1)]

session.begin()
for i in instants:
    for j in intervals:
        session.add(Period1(i, i + j))
        session.add(Period2(i, j))
session.commit()

session.expunge_all()

for ptype in (Period1, Period2):
    q = session.query(ptype)
    for p in q.filter(ptype.length < timedelta(10)):
        print p, p.length
    for p in q.filter(ptype.end < date.today()):
        print p, p.length
    now = datetime.now()
    for p in q.filter(ptype.contains(now)):
        print p, p.contains(now)
    other = Period2(datetime.now(), timedelta(7))
    for p in q.filter(ptype.intersects(other)).order_by(ptype.length):
        print p, p.intersects(other)
"""
-- 
You received this message because you are subscribed to the Google Groups 
"sqlalchemy" group.
To post to this group, send email to sqlalch...@googlegroups.com.
To unsubscribe from this group, send email to 
sqlalchemy+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/sqlalchemy?hl=en.


Reply via email to