2

After I import the modules:

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

I proceed by connecting to 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)

I define and create MyObject's table:

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)

I create 10 MyObject entities:

for i in range(10):
    obj = MyObject()
    session.add(obj)
    session.commit()

I query all the entities by printing their date created:

objects = session.query(MyObject).all()
for obj in objects:
    print obj.created

prints:

2017-01-05 17:22:21
2017-01-05 17:22:21
.
.
.
2017-01-05 17:22:43

Question:

How to query by filtering only those entities that were not created on exactly '2017-01-05 17:22:43'?

I have tried this:

result = session.query(MyObject).filter(MyObject.created!='2017-01-05 17:22:43').all()

But it returns all the objects filtering nothing...

2
  • By default, utcnow() includes microseconds.. are you sure those aren't getting stored in the database? What does the raw record look like? Commented Jan 5, 2017 at 17:47
  • Could you post the result of print str(query) so we can see what SQL is being generated? Commented Jan 5, 2017 at 19:22

1 Answer 1

2

To compare datetimes you will need to convert your string to datetime objects. For e.g. to convert the string 2016-10-20 to datetime you can do so:

from datetime import datetime
print datetime.strptime('2016-10-20', '%Y-%m-%d')

For your question if you are trying to check if the column created doesn't match the time 2017-01-05 17:22:43 then we first convert to datetime object in our query:

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()

You can look up more information on strftime and strptime over here.

Sign up to request clarification or add additional context in comments.

3 Comments

This is incorrect. Datetime comparisons can be made using date strings... So long as they match the format in the database field.
@dizzyf Are you sure it's wrong? Kiran.koduru compares datetimes, not strings
@PiotrDawidiuk In python, comparing datetimes requires datetime objects. But to filter by datetimes in sqlalchemy, string comparisons work just fine... it's not necessary to cast them to an actual python datetime object first. This answer is misleading.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.