Python?SQLAlchemy插入日期時(shí)間時(shí)區(qū)詳解
SQLAlchemy 是一個(gè)功能強(qiáng)大且流行的 Python 庫,它提供了一種靈活有效的與數(shù)據(jù)庫交互的方式。它使用對(duì)象關(guān)系映射(ORM)工具,該工具充當(dāng)Python對(duì)象和關(guān)系數(shù)據(jù)庫之間的橋梁。SQLALchemy提供了多種使用數(shù)據(jù)庫的方法,它提供了高級(jí)別的抽象,使你可以專注于應(yīng)用程序邏輯,同時(shí)使用 Python 與數(shù)據(jù)庫無縫交互。在本文中,我們將了解如何更新日期、時(shí)間和時(shí)區(qū)并將其插入數(shù)據(jù)庫。
在 SQLAlchemy 中使用 DateTime
日期和時(shí)間是數(shù)據(jù)管理的基本方面,在組織和管理數(shù)據(jù)中發(fā)揮著至關(guān)重要的作用。數(shù)據(jù)庫中日期、時(shí)間和時(shí)區(qū)的組合可實(shí)現(xiàn)調(diào)度、歷史跟蹤、合規(guī)性審核和臨時(shí)查詢等任務(wù)。
插入日期、時(shí)間和時(shí)區(qū)
第1步:導(dǎo)入必要的模塊
Stary 通過導(dǎo)入SQLAlchemy 模塊和 DateTime 模塊所需的功能
form datetime import datetime import sqlalchemy from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from sqlalchemy.ext.declarative import declarative_base
第2步:創(chuàng)建基類
使用 declarative_base() 創(chuàng)建基類。它充當(dāng)模型類的父類。
base_class=declarative_base()
第 3 步:建立連接
使用 create_engine() 構(gòu)造函數(shù)建立與數(shù)據(jù)庫的連接
Syntax: engine= create_engine("database :// user:password@host:port/database name")如果你使用 MySql,語法將是
engine = create_engine("mysql+pymysql://user:pass@host:3306/database name")pymysql:是一個(gè)數(shù)據(jù)庫 API 模塊,用于使用 SQLAlchemy 連接到 MySQL 服務(wù)器。我們還需要安裝這個(gè)模塊,以便使用 pip 命令連接到 MySQL 服務(wù)器
pip install pymysql
第四步 :創(chuàng)建模型類
創(chuàng)建一個(gè)表示數(shù)據(jù)庫表的模型類。模型類應(yīng)該繼承基類,并且模型類應(yīng)該有一個(gè)名為 tablename 的強(qiáng)制屬性,它表示表的名稱。
class model_class(base_class):
__tablename__="name of table"
//Attributes第 5步:創(chuàng)建會(huì)話********
使用sessionmaker()方法創(chuàng)建會(huì)話對(duì)象并將其綁定到數(shù)據(jù)庫引擎
sessionMaker=sessionmaker(bind=engine)
第6步:創(chuàng)建數(shù)據(jù)庫表
在這一步中,我們使用 create_all 方法創(chuàng)建數(shù)據(jù)庫表。如果數(shù)據(jù)庫已經(jīng)包含表,則不需要這些九月
base_class.metadata.create_all(engine)
第 7 步:創(chuàng)建日期時(shí)間對(duì)象:
為所需的日期時(shí)間或具有指定時(shí)區(qū)的今天的日期時(shí)間創(chuàng)建日期時(shí)間類對(duì)象。這里我們使用Python的datetime模塊來獲取日期、時(shí)間。
dateTimeObj=datetime.datetime(year, month, day, hour, minute, second, tzinfo)
這里 tzinfo 指定時(shí)區(qū),可以從python的 pytz模塊獲取
步驟8:創(chuàng)建表行(創(chuàng)建實(shí)例模型類)
使用適當(dāng)?shù)膶傩灾祫?chuàng)建模型類的實(shí)例
modelClassObject = model_class(attribute values)
第9步:模型實(shí)例
使用 add() 方法將模型類的實(shí)例添加到會(huì)話中(將數(shù)據(jù)插入表中)
session.add(modelClassObject)
第 10 步:提交更改
將數(shù)據(jù)添加到會(huì)話后,將更改提交到數(shù)據(jù)庫。
session.commit()
注意:如果你不使用提交方法,則更改不會(huì)影響數(shù)據(jù)庫。
第11步:關(guān)閉連接
使用 close() 關(guān)閉會(huì)話。
session.close()
示例:創(chuàng)建 SQLAlchemy DateTime 類的實(shí)例
在給定的示例中,我們創(chuàng)建 DateTime 類的三個(gè)實(shí)例,每個(gè)實(shí)例代表一個(gè)特定的日期和時(shí)間及其各自的時(shí)區(qū)。第一個(gè)對(duì)象表示時(shí)區(qū)“歐洲/倫敦”中的日期和時(shí)間“2020-05-23 10:30:30”。第二個(gè)對(duì)象表示時(shí)區(qū)“America/New_York”中的日期和時(shí)間“2022-12-30 18:30:30”。第三個(gè)對(duì)象表示當(dāng)前日期和時(shí)間,時(shí)區(qū)設(shè)置為當(dāng)前時(shí)區(qū)。然后利用這些實(shí)例將員工數(shù)據(jù)插入表中。
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'
# 我們需要有一個(gè)主鍵,否則將不會(huì)創(chuàng)建表
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))
# 替換為你的創(chuàng)建者和數(shù)據(jù)庫名稱
engine = create_engine("mysql+pymysql://user:password@host/dbName")
Session = sessionmaker(bind=engine)
session = Session()
print("connection established...")
# 創(chuàng)建不存在的表
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() 方法直接給出今天的日期和當(dāng)前時(shí)間
Obj3 = datetime.datetime.now()
todayDate = Obj3.date()
todayTime = Obj3.time()
# 當(dāng)前時(shí)區(qū)
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 與當(dāng)前時(shí)區(qū)
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)
# 將實(shí)例添加到會(huì)話
session.add_all([employee1, employee2, employee3,
employee4, employee5, employee6])
print("successfully data added to session")
# 提交更改
session.commit()
print("successfully inserted data")
# 關(guān)閉數(shù)據(jù)庫連接
session.close()
print("DB connection closed")員工表:

在 SQLAlchemy 中更新日期、時(shí)間和時(shí)區(qū)
在 SQLAlchemy 中,我們可以使用 query() 方法和 update() 方法更新 DATE 和 TIME
通過使用query()
在此示例中,我們首先創(chuàng)建一個(gè)引擎和會(huì)話來連接到數(shù)據(jù)庫。然后,我們使用 query() 和 filter() 方法檢索時(shí)區(qū)為“歐洲/倫敦”且 “hire_date”不等于今天日期的員工的數(shù)據(jù)。接下來,我們將其“hire_date”和“hire_time”** 字段更新為當(dāng)前日期和時(shí)間。
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)
# 查詢數(shù)據(jù)
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()
# 關(guān)閉數(shù)據(jù)庫連接
session.close()更新后:

通過使用 update()
update():它允許您修改數(shù)據(jù)庫表中的現(xiàn)有記錄。它構(gòu)造一個(gè) SQL UPDATE 語句,以根據(jù)指定條件更改表中一列或多列的值。
語法: update(表名).where(條件).values(col1=newValue,col2=newValue..)
在以下示例中,我們執(zhí)行更新操作,將時(shí)區(qū)與當(dāng)前時(shí)區(qū)匹配的員工的工資增加 25000。
# 時(shí)區(qū)
timeZone=pytz.timezone("Asia/Kolkata")
# 正在創(chuàng)建更新quey
query=update(Employee).where(Employee.time_zone==timeZone).values(salary=Employee.salary+25000)
# 使用DB執(zhí)行
session.execute(query)
# 提交更改
session.commit()
# 關(guān)閉數(shù)據(jù)庫連接
session.close()更新后:

在 SQLAlchemy 中過濾日期、時(shí)間和時(shí)區(qū)
通過使用query()和filter()
在以下示例中,我們將檢索時(shí)區(qū)與當(dāng)前時(shí)區(qū)匹配或雇用日期等于 2022-12-30 的所有員工的數(shù)據(jù)。
# 為2022-12-30創(chuàng)建日期時(shí)間對(duì)象
dateTimeObj = datetime.datetime(year=2022, month=12, day=30)
# 日期
date = dateTimeObj.date()
# 時(shí)區(qū)
currentTimeZone = pytz.timezone("Asia/Kolkata")
# 查詢員工詳細(xì)信息
empData = session.query(Employee).filter(
or_(Employee.time_zone == currentTimeZone, Employee.hire_date == date)).all()
# 打印數(shù)據(jù)
for emp in empData:
print(emp.id, emp.name, emp.hire_date, emp.time_zone)
session.close()輸出:

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 歲且時(shí)區(qū)為 Asia/Kolkata 或 America/New_York 的員工的數(shù)據(jù)。
# 亞洲/加爾各答時(shí)區(qū)
timeZone1 = pytz.timezone("Asia/Kolkata")
# 美國(guó)/紐約時(shí)區(qū)
timeZone2 = pytz.timezone("America/New_york")
# 創(chuàng)建SELECT語句
statement = select(Employee).where(and_(Employee.age >= 40, or_(
Employee.time_zone == timeZone1, Employee.time_zone == timeZone2)))
# 使用數(shù)據(jù)庫執(zhí)行
result = session.execute(statement).fetchall()
# 打印結(jié)果
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()輸出:

3 Dhoni 54 75000
4 Kohli 55 150000
6 Ravi 45 50000
以上就是Python SQLAlchemy插入日期時(shí)間時(shí)區(qū)詳解的詳細(xì)內(nèi)容,更多關(guān)于Python SQLAlchemy的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Pytorch實(shí)現(xiàn)圖像識(shí)別之?dāng)?shù)字識(shí)別(附詳細(xì)注釋)
這篇文章主要介紹了Pytorch實(shí)現(xiàn)圖像識(shí)別之?dāng)?shù)字識(shí)別(附詳細(xì)注釋),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-05-05
Python+Kepler.gl實(shí)現(xiàn)時(shí)間輪播地圖過程解析
這篇文章主要介紹了Python+Kepler.gl實(shí)現(xiàn)時(shí)間輪播地圖過程解析,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-07-07
PyTorch CUDA環(huán)境配置及安裝的步驟(圖文教程)
這篇文章主要介紹了PyTorch CUDA環(huán)境配置及安裝的步驟(圖文教程),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-04-04
Python自動(dòng)化測(cè)試框架之unittest使用詳解
unittest是Python自動(dòng)化測(cè)試框架之一,提供了一系列測(cè)試工具和接口,支持單元測(cè)試、功能測(cè)試、集成測(cè)試等多種測(cè)試類型。unittest使用面向?qū)ο蟮乃枷雽?shí)現(xiàn)測(cè)試用例的編寫和管理,可以方便地?cái)U(kuò)展和定制測(cè)試框架,支持多種測(cè)試結(jié)果輸出格式2023-04-04

