Python?SQLAlchemy插入日期時間時區(qū)詳解
SQLAlchemy 是一個功能強大且流行的 Python 庫,它提供了一種靈活有效的與數(shù)據(jù)庫交互的方式。它使用對象關(guān)系映射(ORM)工具,該工具充當(dāng)Python對象和關(guān)系數(shù)據(jù)庫之間的橋梁。SQLALchemy提供了多種使用數(shù)據(jù)庫的方法,它提供了高級別的抽象,使你可以專注于應(yīng)用程序邏輯,同時使用 Python 與數(shù)據(jù)庫無縫交互。在本文中,我們將了解如何更新日期、時間和時區(qū)并將其插入數(shù)據(jù)庫。
在 SQLAlchemy 中使用 DateTime
日期和時間是數(shù)據(jù)管理的基本方面,在組織和管理數(shù)據(jù)中發(fā)揮著至關(guān)重要的作用。數(shù)據(jù)庫中日期、時間和時區(qū)的組合可實現(xiàn)調(diào)度、歷史跟蹤、合規(guī)性審核和臨時查詢等任務(wù)。
插入日期、時間和時區(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:是一個數(shù)據(jù)庫 API 模塊,用于使用 SQLAlchemy 連接到 MySQL 服務(wù)器。我們還需要安裝這個模塊,以便使用 pip 命令連接到 MySQL 服務(wù)器
pip install pymysql
第四步 :創(chuàng)建模型類
創(chuàng)建一個表示數(shù)據(jù)庫表的模型類。模型類應(yīng)該繼承基類,并且模型類應(yīng)該有一個名為 tablename 的強制屬性,它表示表的名稱。
class model_class(base_class): __tablename__="name of table" //Attributes
第 5步:創(chuàng)建會話********
使用sessionmaker()方法創(chuàng)建會話對象并將其綁定到數(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)建日期時間對象:
為所需的日期時間或具有指定時區(qū)的今天的日期時間創(chuàng)建日期時間類對象。這里我們使用Python的datetime模塊來獲取日期、時間。
dateTimeObj=datetime.datetime(year, month, day, hour, minute, second, tzinfo)
這里 tzinfo 指定時區(qū),可以從python的 pytz模塊獲取
步驟8:創(chuàng)建表行(創(chuàng)建實例模型類)
使用適當(dāng)?shù)膶傩灾祫?chuàng)建模型類的實例
modelClassObject = model_class(attribute values)
第9步:模型實例
使用 add() 方法將模型類的實例添加到會話中(將數(shù)據(jù)插入表中)
session.add(modelClassObject)
第 10 步:提交更改
將數(shù)據(jù)添加到會話后,將更改提交到數(shù)據(jù)庫。
session.commit()
注意:如果你不使用提交方法,則更改不會影響數(shù)據(jù)庫。
第11步:關(guān)閉連接
使用 close() 關(guān)閉會話。
session.close()
示例:創(chuàng)建 SQLAlchemy DateTime 類的實例
在給定的示例中,我們創(chuàng)建 DateTime 類的三個實例,每個實例代表一個特定的日期和時間及其各自的時區(qū)。第一個對象表示時區(qū)“歐洲/倫敦”中的日期和時間“2020-05-23 10:30:30”。第二個對象表示時區(qū)“America/New_York”中的日期和時間“2022-12-30 18:30:30”。第三個對象表示當(dāng)前日期和時間,時區(qū)設(shè)置為當(dāng)前時區(qū)。然后利用這些實例將員工數(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' # 我們需要有一個主鍵,否則將不會創(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)前時間 Obj3 = datetime.datetime.now() todayDate = Obj3.date() todayTime = Obj3.time() # 當(dāng)前時區(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)前時區(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) # 將實例添加到會話 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 中更新日期、時間和時區(qū)
在 SQLAlchemy 中,我們可以使用 query() 方法和 update() 方法更新 DATE 和 TIME
通過使用query()
在此示例中,我們首先創(chuàng)建一個引擎和會話來連接到數(shù)據(jù)庫。然后,我們使用 query() 和 filter() 方法檢索時區(qū)為“歐洲/倫敦”且 “hire_date”不等于今天日期的員工的數(shù)據(jù)。接下來,我們將其“hire_date”和“hire_time”** 字段更新為當(dāng)前日期和時間。
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)造一個 SQL UPDATE 語句,以根據(jù)指定條件更改表中一列或多列的值。
語法: update(表名).where(條件).values(col1=newValue,col2=newValue..)
在以下示例中,我們執(zhí)行更新操作,將時區(qū)與當(dāng)前時區(qū)匹配的員工的工資增加 25000。
# 時區(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 中過濾日期、時間和時區(qū)
通過使用query()和filter()
在以下示例中,我們將檢索時區(qū)與當(dāng)前時區(qū)匹配或雇用日期等于 2022-12-30 的所有員工的數(shù)據(jù)。
# 為2022-12-30創(chuàng)建日期時間對象 dateTimeObj = datetime.datetime(year=2022, month=12, day=30) # 日期 date = dateTimeObj.date() # 時區(qū) currentTimeZone = pytz.timezone("Asia/Kolkata") # 查詢員工詳細信息 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 歲且時區(qū)為 Asia/Kolkata 或 America/New_York 的員工的數(shù)據(jù)。
# 亞洲/加爾各答時區(qū) timeZone1 = pytz.timezone("Asia/Kolkata") # 美國/紐約時區(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插入日期時間時區(qū)詳解的詳細內(nèi)容,更多關(guān)于Python SQLAlchemy的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Pytorch實現(xiàn)圖像識別之?dāng)?shù)字識別(附詳細注釋)
這篇文章主要介紹了Pytorch實現(xiàn)圖像識別之?dāng)?shù)字識別(附詳細注釋),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-05-05Python+Kepler.gl實現(xiàn)時間輪播地圖過程解析
這篇文章主要介紹了Python+Kepler.gl實現(xiàn)時間輪播地圖過程解析,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-07-07PyTorch CUDA環(huán)境配置及安裝的步驟(圖文教程)
這篇文章主要介紹了PyTorch CUDA環(huán)境配置及安裝的步驟(圖文教程),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-04-04