SQLAlchemy 中的日期时间时区

SQLAlchemy 是一个功能强大且流行的 Python 库,它提供了一种灵活有效的与数据库交互的方式。它使用对象关系映射(ORM)工具,该工具充当Python对象和关系数据库之间的桥梁。SQLALchemy提供了多种使用数据库的方法,它提供了高级别的抽象,使你可以专注于应用程序逻辑,同时使用 Python 与数据库无缝交互。在本文中,我们将了解如何更新日期、时间和时区并将其插入数据库。

在 SQLAlchemy 中使用 DateTime

日期和时间是数据管理的基本方面,在组织和管理数据中发挥着至关重要的作用。数据库中日期、时间和时区的组合可实现调度、历史跟踪、合规性审核和临时查询等任务。

插入日期、时间和时区

第1步:导入必要的模块

Stary 通过导入SQLAlchemy 模块和 DateTime 模块所需的功能

python 复制代码
form datetime import datetime
import sqlalchemy
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base

第2步:创建基类

使用 declarative_base() 创建基类。它充当模型类的父类。

python 复制代码
base_class=declarative_base()

第 3 步:建立连接

使用 create_engine() 构造函数建立与数据库的连接

python 复制代码
Syntax: engine= create_engine("database :// user:password@host:port/database name")

如果你使用 MySql,语法将是

python 复制代码
engine = create_engine("mysql+pymysql://user:pass@host:3306/database name")

pymysql:是一个数据库 API 模块,用于使用 SQLAlchemy 连接到 MySQL 服务器。我们还需要安装这个模块,以便使用 pip 命令连接到 MySQL 服务器

python 复制代码
pip install pymysql

第四步 :创建模型类

创建一个表示数据库表的模型类。模型类应该继承基类,并且模型类应该有一个名为 tablename 的强制属性,它表示表的名称。

python 复制代码
class model_class(base_class):
    __tablename__="name of table"
    //Attributes

第 5步创建会话********

使用sessionmaker()方法创建会话对象并将其绑定到数据库引擎

python 复制代码
sessionMaker=sessionmaker(bind=engine)

第6步:创建数据库表

在这一步中,我们使用 create_all 方法创建数据库表。如果数据库已经包含表,则不需要这些九月

python 复制代码
base_class.metadata.create_all(engine)

第 7 步:创建日期时间对象:

为所需的日期时间或具有指定时区的今天的日期时间创建日期时间类对象。这里我们使用Python的datetime模块来获取日期、时间。

python 复制代码
dateTimeObj=datetime.datetime(year, month, day, hour, minute, second, tzinfo)

这里 tzinfo 指定时区,可以从python的 pytz模块获取

步骤8:创建表行(创建实例模型类)

使用适当的属性值创建模型类的实例

python 复制代码
modelClassObject = model_class(attribute values)

第9步:模型实例

使用 add() 方法将模型类的实例添加到会话中(将数据插入表中)

python 复制代码
session.add(modelClassObject)

第 10 步:提交更改

将数据添加到会话后,将更改提交到数据库。

python 复制代码
session.commit()

注意:如果你不使用提交方法,则更改不会影响数据库。

第11步:关闭连接

使用 close() 关闭会话。

python 复制代码
session.close()

示例:创建 SQLAlchemy DateTime 类的实例

在给定的示例中,我们创建 DateTime 类的三个实例,每个实例代表一个特定的日期和时间及其各自的时区。第一个对象表示时区"欧洲/伦敦"中的日期和时间"2020-05-23 10:30:30"。第二个对象表示时区"America/New_York"中的日期和时间"2022-12-30 18:30:30"。第三个对象表示当前日期和时间,时区设置为当前时区。然后利用这些实例将员工数据插入表中。

python 复制代码
import datetime
import pytz
from sqlalchemy import *
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base

# 基类
base_class = declarative_base()

# 模型类
class Employee(base_class):
	__tablename__ = 'employee'
	# 我们需要有一个主键,否则将不会创建表
	id = Column(Integer, primary_key=True)
	name = Column(String(50))
	age = Column(Integer)
	salary = Column(DECIMAL)

	hire_date = Column(Date)
	hire_time = Column(Time)
	time_zone = Column(String(500))


# 替换为你的创建者和数据库名称
engine = create_engine("mysql+pymysql://user:password@host/dbName")

Session = sessionmaker(bind=engine)
session = Session()
print("connection established...")

# 创建不存在的表
base_class.metadata.create_all(engine)
print("table created...")

Obj1 = datetime.datetime(year=2020, month=5, day=23, hour=10,
						minute=30, second=30, tzinfo=pytz.timezone("Europe/London"))

Obj2 = datetime.datetime(year=2022, month=12, day=30, hour=18,
						minute=30, second=30, tzinfo=pytz.timezone("America/New_York"))

# datetime 的 now() 方法直接给出今天的日期和当前时间
Obj3 = datetime.datetime.now()
todayDate = Obj3.date()
todayTime = Obj3.time()

# 当前时区
currentTimeZone = current_timezone = pytz.timezone(
	pytz.country_timezones['IN'][0])
print("currnet time zone=", currentTimeZone)

employee1 = Employee(id=1, name="Alice", age=25, salary=50000,
					hire_date=Obj1.date(), hire_time=Obj1.time(), time_zone=Obj1.tzinfo)
employee2 = Employee(id=2, name="Bod", age=34, salary=55000,
					hire_date=todayDate, hire_time=todayTime, time_zone=Obj1.tzinfo)

employee3 = Employee(id=3, name="Dhoni", age=54, salary=75000,
					hire_date=Obj2.date(), hire_time=Obj2.time(), time_zone=Obj2.tzinfo)
employee4 = Employee(id=4, name="Kohli", age=55, salary=150000,
					hire_date=todayDate, hire_time=todayTime, time_zone=Obj2.tzinfo)

# emp5 和 emp6 与当前时区
employee5 = Employee(id=5, name="Raju", age=35, salary=65000, hire_date=Obj1.date(
), hire_time=Obj1.time(), time_zone=currentTimeZone)
employee6 = Employee(id=6, name="Ravi", age=45, salary=25000,
					hire_date=todayDate, hire_time=todayTime, time_zone=currentTimeZone)


# 将实例添加到会话
session.add_all([employee1, employee2, employee3,
				employee4, employee5, employee6])
print("successfully data added to session")

# 提交更改
session.commit()
print("successfully inserted data")

# 关闭数据库连接
session.close()
print("DB connection closed")

员工表:

在 SQLAlchemy 中更新日期、时间和时区

在 SQLAlchemy 中,我们可以使用 query() 方法和 update() 方法更新 DATE 和 TIME

通过使用query()

在此示例中,我们首先创建一个引擎和会话来连接到数据库。然后,我们使用 query() 和 filter() 方法检索时区为"欧洲/伦敦"且 "hire_date"不等于今天日期的员工的数据。接下来,我们将其"hire_date"和"hire_time"** 字段更新为当前日期和时间。

python 复制代码
import datetime
import pytz
from sqlalchemy import *
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base

# 基类
base_class = declarative_base()

# 模型类
class Employee(base_class):
	__tablename__ = 'employee'
	id = Column(Integer, primary_key=True)
	name = Column(String(50))
	age = Column(Integer)
	salary = Column(DECIMAL)

	hire_date = Column(Date)
	hire_time = Column(Time)
	time_zone = Column(String(500))


engine = create_engine("mysql+pymysql://user:Password@host/dbName")

Session = sessionmaker(bind=engine)
session = Session()

dateTimeObj = datetime.datetime.now()
timeZone = pytz.timezone("Europe/London")

date = dateTimeObj.date()
time = dateTimeObj.time()
print(timeZone, date, time)

# 查询数据
employeeDate = session.query(Employee).filter(
	and_(Employee.time_zone == timeZone, Employee.hire_date != date)).all()

# 更新 hire_date 和 hire_time
for employee in employeeDate:
	employee.hire_date = date
	employee.hire_time = time

# 提交更改
session.commit()

# 关闭数据库连接
session.close()

更新后:

通过使用 update():

update():它允许您修改数据库表中的现有记录。它构造一个 SQL UPDATE 语句,以根据指定条件更改表中一列或多列的值。

语法: update(表名).where(条件).values(col1=newValue,col2=newValue..)

在以下示例中,我们执行更新操作,将时区与当前时区匹配的员工的工资增加 25000。

python 复制代码
# 时区
timeZone=pytz.timezone("Asia/Kolkata")

# 正在创建更新quey
query=update(Employee).where(Employee.time_zone==timeZone).values(salary=Employee.salary+25000)

# 使用DB执行
session.execute(query)

# 提交更改
session.commit()

# 关闭数据库连接
session.close()

更新后:

在 SQLAlchemy 中过滤日期、时间和时区

通过使用query()和filter()

在以下示例中,我们将检索时区与当前时区匹配或雇用日期等于 2022-12-30 的所有员工的数据。

python 复制代码
# 为2022-12-30创建日期时间对象
dateTimeObj = datetime.datetime(year=2022, month=12, day=30)

# 日期
date = dateTimeObj.date()

# 时区
currentTimeZone = pytz.timezone("Asia/Kolkata")

# 查询员工详细信息
empData = session.query(Employee).filter(
	or_(Employee.time_zone == currentTimeZone, Employee.hire_date == date)).all()

# 打印数据
for emp in empData:
	print(emp.id, emp.name, emp.hire_date, emp.time_zone)

session.close()

输出:

python 复制代码
3 Dhoni 2022-12-30 America/New_York
5 Raju 2020-05-23 Asia/Kolkata
6 Ravi 2023-06-15 Asia/Kolkata

通过使用 select() 和 where()

在以下示例中,我们检索年龄大于或等于 40 岁且时区为 Asia/Kolkata 或 America/New_York 的员工的数据。

python 复制代码
# 亚洲/加尔各答时区
timeZone1 = pytz.timezone("Asia/Kolkata")

# 美国/纽约时区
timeZone2 = pytz.timezone("America/New_york")

# 创建SELECT语句
statement = select(Employee).where(and_(Employee.age >= 40, or_(
	Employee.time_zone == timeZone1, Employee.time_zone == timeZone2)))

# 使用数据库执行
result = session.execute(statement).fetchall()

# 打印结果
print("By using the select() and where()")
for emp in result:
	print(emp[0].id, emp[0].name, emp[0].age, emp[0].salary)

session.close()

输出:

python 复制代码
3 Dhoni 54 75000
4 Kohli 55 150000
6 Ravi 45 50000
相关推荐
用户685453759776939 分钟前
同步成本换并行度:多线程、协程、分片、MapReduce 怎么选才不踩坑
后端
javaTodo1 小时前
Claude Code 记忆机制详解:从 CLAUDE.md 到 Auto Memory,六层体系全拆解
后端
LSTM971 小时前
使用 C# 和 Spire.PDF 从 HTML 模板生成 PDF 的实用指南
后端
JaguarJack1 小时前
为什么 PHP 闭包要加 static?
后端·php·服务端
BingoGo1 小时前
为什么 PHP 闭包要加 static?
后端
是糖糖啊2 小时前
OpenClaw 从零到一实战指南(飞书接入)
前端·人工智能·后端
百度Geek说2 小时前
基于Spark的配置化离线反作弊系统
后端
Java编程爱好者2 小时前
虚拟线程深度解析:轻量并发编程的未来趋势
后端
苏三说技术3 小时前
Spring AI 和 LangChain4j ,哪个更好?
后端