So, I found out how to achieve what I wanted. Thanks to @univerio for the corrections!
I'll post the entire IPython Notebook session :)
In [1]:
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Unicode, DateTime, Integer, create_engine
from sqlalchemy.orm import sessionmaker, relationship, backref
import datetime
engine = create_engine('sqlite:///:memory:')
Base = declarative_base()
Session = sessionmaker(bind=engine)
session = Session()
In [2]:
class Product(Base):
__tablename__ = "product"
id = Column(Integer, primary_key=True)
name = Column(Unicode(140), unique=True, nullable=False)
department = Column(Unicode(20))
added = Column(DateTime, default=datetime.datetime.now)
last_time_parsed = Column(DateTime)
def repr(self):
return "<Product(name=%s, department=%s, added=%s, last_time_parsed=%s)>" % (
self.name, self.department, self.added, self.last_time_parsed)
In [3]:
# create the tables
Base.metadata.create_all(engine)
In [4]:
# create a false product
twodaysinthefuture = datetime.datetime.now() + datetime.timedelta(hours=48)
p1 = Product(name="Product X")
p2 = Product(name = "Product Y")
p3 = Product(name = "Product Z")
x1 = Product(name = "Product older than 24 hours 1", last_time_parsed=twodaysinthefuture)
x2 = Product(name = "Product older than 24 hours 2", last_time_parsed=twodaysinthefuture)
x3 = Product(name = "Product older than 24 hours 3", last_time_parsed=twodaysinthefuture)
In [5]:
session.add(p1)
session.add(p2)
session.add(p3)
session.add(x1)
session.add(x2)
session.add(x3)
session.commit()
/home/jorge/coders/PPH/clientes/robert_s/playcomscrap/lib/python2.7/site-packages/sqlalchemy/engine/default.py:525: SAWarning: Unicode type received non-unicode bind param value.
param.append(processors[key](compiled_params[key]))
In [6]:
onedayearly = datetime.timedelta(hours=24)
print onedayearly
since = datetime.datetime.now() - onedayearly
1 day, 0:00:00
In [7]:
q1 = session.query(Product).filter(Product.last_time_parsed < since) # filter-out those rows with less than 24 hours, right?
q2 = session.query(Product).filter(Product.last_time_parsed == None) # I'm interested on those products with no time stamp yet, too.
q3 = q1.union(q2).order_by(Product.id) # aaaaand, done!
In [8]:
# testing
for row in q3.all():
print row.name, row.last_time_parsed
Product X None
Product Y None
Product Z None
Product older than 24 hours 1 2014-03-17 17:26:03.899875
Product older than 24 hours 2 2014-03-17 17:26:03.899875
Product older than 24 hours 3 2014-03-17 17:26:03.899875
In []: