📅  最后修改于: 2023-12-03 15:35:06.867000             🧑  作者: Mango
SQLAlchemy is a Python SQL toolkit and Object-Relational Mapping (ORM) library that provides a set of high-level API to interact with SQL databases. It has a powerful SQL expression language that enables you to generate SQL queries easily.
One common task when working with SQL databases is to extract records that fall in a particular date range. In this tutorial, we'll see how to use SQLAlchemy to perform a date range query in a database.
To follow along with this tutorial, ensure that you have the following:
Before we can perform a date range query, we first need to connect to a database using SQLAlchemy. The following code demonstrates how to connect to a SQLite database:
from sqlalchemy import create_engine
engine = create_engine('sqlite:///test.db')
To extract records between two dates using SQLAlchemy, we'll first create a table that contains a date column. For the purpose of this tutorial, we'll create a simple table called "users" with a "created_at" column that stores the date a user was created:
from sqlalchemy import create_engine, Column, Integer, String, Date
from sqlalchemy.orm import declarative_base
Base = declarative_base()
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String)
created_at = Column(Date)
We'll then create a session object:
from sqlalchemy.orm import sessionmaker
Session = sessionmaker(bind=engine)
session = Session()
To extract users created between 2010-01-01 and 2011-01-01, we can use the between()
method of the date column as follows:
from datetime import datetime
# Create a start and end date
start_date = datetime(2010, 1, 1).date()
end_date = datetime(2011, 1, 1).date()
# Query the database for users created between the start and end date
users = session.query(User).filter(User.created_at.between(start_date, end_date)).all()
# Print the results
for user in users:
print(user.name, user.created_at)
In this tutorial, we learned how to use SQLAlchemy to perform a date range query in a database. We created a simple table with a date column and extracted users created between two dates using the between()
method of the date column. SQLAlchemy is a powerful SQL toolkit that provides a high-level API for interacting with SQL databases.