导入模块后:
import datetime, uuid
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy import Column, ForeignKey, Integer, String, DateTime, create_engine, literal
我继续连接到db:
Base = declarative_base()
session = scoped_session(sessionmaker())
engine = create_engine('mysql://root:pass@localhost/testdb', echo=False)
session.remove()
session.configure(bind=engine, autoflush=False, expire_on_commit=False)
我定义并创建了MyObject的表:
class MyObject(Base):
__tablename__ = 'myobjects'
uuid = Column(String(64), primary_key=True, unique=True)
created = Column(DateTime, nullable=False)
def __init__ (self, *args, **kwargs):
self.uuid = str(uuid.uuid4()).replace('-','').lower()
self.created = datetime.datetime.utcnow()
Base.metadata.create_all(engine)
我创建了10个MyObject
个实体:
for i in range(10):
obj = MyObject()
session.add(obj)
session.commit()
我通过打印创建的日期来查询所有实体:
objects = session.query(MyObject).all()
for obj in objects:
print obj.created
打印:
2017-01-05 17:22:21
2017-01-05 17:22:21
.
.
.
2017-01-05 17:22:43
问题:
如何通过仅过滤那些未在'2017-01-05 17:22:43'上创建的实体进行查询?
我试过这个:
result = session.query(MyObject).filter(MyObject.created!='2017-01-05 17:22:43').all()
但它会返回所有过滤任何内容的对象......
答案 0 :(得分:2)
要比较datetimes
,您需要将string
转换为datetime
个对象。对于例如要将字符串2016-10-20
转换为datetime
,您可以这样做:
from datetime import datetime
print datetime.strptime('2016-10-20', '%Y-%m-%d')
对于您的问题,如果您要检查列created
是否与时间2017-01-05 17:22:43
不匹配,那么我们首先在查询中转换为datetime
对象:
from datetime import datetime
search_created = datetime.strptime('2017-01-05 17:22:43', '%Y-%m-%d %H:%M:%S')
result = session.query(MyObject).filter(MyObject.created!=search_created).all()
您可以在strftime
和strptime
上查看有关here的更多信息。