sqlite3日期数据类型

简介:

一、sqlite3日期数据类型,默认用datetime解析(根据stackflow

使用时注意三点:

  1. 创建表时,字段 DT 的类型为 date

  2. 插入数据时,DT字段直接为 str 类型

  3. DT字段的str ,年月日必须为 xxxx-xx-xx 格式,如 2016-01-01,不能是 2016-1-1

复制代码
import sqlite3
import datetime

'''sqlite3日期数据类型'''
con = sqlite3.connect(":memory:") c = con.cursor() # Create table c.execute('''CREATE TABLE marksix (DT date, Period text, P1 int, P2 int, P3 int, P4 int, P5 int, P6 int, T7 int)''') # Larger example that inserts many records at a time purchases = [('2016-01-01', '2016001', 2, 36, 23, 43, 12, 25, 29), ('2016-01-03', '2016002', 34, 35, 17, 49, 24, 30, 16), ('2016-01-05', '2016003', 1, 35, 12, 49, 49, 26, 34), ('2016-01-08', '2016004', 6, 35, 10, 40, 4, 23, 2), ('2016-01-10', '2016005', 14, 35, 27, 40, 4, 12, 45), ('2016-01-12', '2016006', 33, 10, 13, 21, 27, 22, 17), ('2016-01-15', '2016007', 20, 35, 17, 49, 5, 29, 28), ] c.executemany('INSERT INTO marksix (DT,Period,P1,P2,P3,P4,P5,P6,T7) VALUES (?,?,?,?,?,?,?,?,?)', purchases)
for row in c.execute('SELECT * FROM marksix'): print(row)
# ==============================================================

# 方式一:显式使用 datetime 类型 t = datetime.datetime.strptime('2016-1-5', '%Y-%m-%d') dt = (datetime.date(t.year, t.month, t.day), ) for row in c.execute('SELECT * FROM marksix WHERE DT = ?', dt): print(row) # 方式二:直接使用 str 类型 dt = ('2016-01-05', ) for row in c.execute('SELECT * FROM marksix WHERE DT = ?', dt): print(row)


#for row in c.execute('SELECT * FROM marksix WHERE dt BETWEEN :begin AND :end;', {"begin": '2016-01-03', "end": '2016-01-11'}): for row in c.execute('SELECT * FROM marksix WHERE dt BETWEEN ? AND ?;', ('2016-01-03', '2016-01-11')): print(row)
复制代码

 

二、另一种方式使用时间类型数据(根据官网文档

复制代码
import sqlite3
import datetime


# 适配器
def adapt_date(date):
    return datetime.datetime.strftime('%Y/%m/%d', date)
    #return date.strftime('%Y/%m/%d').encode('ascii')
    #return date.strftime('%Y/%m/%d').encode()

# 转换器
def convert_date(string):
    return datetime.datetime.strptime(string.decode(), '%Y/%m/%d')

# 注册适配器
sqlite3.register_adapter(datetime.datetime, adapt_date)

# 注册转换器
sqlite3.register_converter("date", convert_date)




# 注意:detect_types=sqlite3.PARSE_DECLTYPES
con = sqlite3.connect(":memory:", detect_types=sqlite3.PARSE_DECLTYPES)
c = con.cursor()


# Create table
c.execute('''CREATE TABLE marksix
            (dt date, period text, p1 int, p2 int, p3 int, p4 int, p5 int, p6 int, t7 int)''')


# Larger example that inserts many records at a time
purchases = [('2016/1/1', '2016001', 2, 36, 23, 43, 12, 25, 29),
             ('2016/1/3', '2016002', 34, 35, 17, 49, 24, 30, 16),
             ('2016/1/5', '2016003', 1, 35, 12, 49, 49, 26, 34),
             ('2016/1/8', '2016004', 6, 35, 10, 40, 4, 23, 2),
             ('2016/1/10', '2016005', 14, 35, 27, 40, 4, 12, 45),
             ('2016/1/12', '2016006', 33, 10, 13, 21, 27, 22, 17),
             ('2016/1/15', '2016007', 20, 35, 17, 49, 5, 29, 28),
            ]
c.executemany('INSERT INTO marksix VALUES (?,?,?,?,?,?,?,?,?)', purchases)

# Save (commit) the changes
con.commit()

for row in c.execute('SELECT * FROM marksix'):
    print(row)

# ==============================================================

# 显示日期等于2016/1/3的记录
t = ('2016/1/3',)
c.execute('SELECT * FROM marksix WHERE dt = ?', t)
print(c.fetchone())



# 貌似不支持between运算,不知原因!
for row in c.execute('SELECT * FROM marksix WHERE dt BETWEEN ? AND ?;', ('2016/1/3', '2016/1/11')):
    print(row)
复制代码

 

三、还有一种日期时间类型:timestamp(时间戳)

复制代码
import datetime


# Converting SQLite values to custom Python types
# Default adapters and converters for datetime and timestamp
con = sqlite3.connect(":memory:", detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES)
cur = con.cursor()

cur.execute('''create table test(
                                d date, 
                                ts timestamp
                                )''')

# 插入datetime类型
today = datetime.date.today()
now = datetime.datetime.now()
day1 = datetime.timedelta(days=1)
data = [(today-day1, now-day1),
        (today, now),
        (today+day1, now+day1)]
cur.executemany("insert into test(d, ts) values (?, ?)", data)

# 插入 str 类型
data = [('2016-01-22', '2016-01-22 08:45:50'),
        ('2016-02-22', '2016-02-22 08:45:50'),
        ('2016-03-22', '2016-03-22 08:45:50')]
cur.executemany("insert into test(d, ts) values (?, ?)", data)
        

for row in cur.execute("select * from test"):
    print(row)

#=================================================================

#begin = datetime.date(2016, 2, 22)
#end = datetime.date(2016, 2, 23)
begin = '2016-02-22'
end = '2016-02-23'
for row in cur.execute("select * from test where d BETWEEN ? AND ?", (begin, end)):
    print(row)


begin = datetime.datetime(2016, 2, 22, 8, 45, 50, 0)
end = datetime.datetime(2016, 2, 23, 20, 10, 47, 12345)
#begin = '2016-02-22 08:45:50'
#end = '2016-02-23 20:10:47'
for row in cur.execute("select * from test where ts BETWEEN ? AND ?", (begin, end)):
    print(row)
复制代码

 

本文转自罗兵博客园博客,原文链接:http://www.cnblogs.com/hhh5460/p/5205982.html ,如需转载请自行联系原作者
相关文章
|
NoSQL Linux Redis
在Windows下使用msys2编译最新版的Redis
在Windows下使用msys2编译最新版的Redis
2047 0
|
SQL 关系型数据库 MySQL
Java 最常见的面试题:如何做 mysql 的性能优化?
Java 最常见的面试题:如何做 mysql 的性能优化?
|
9月前
|
机器学习/深度学习 边缘计算 算法
【无人机】无人机群在三维环境中的碰撞和静态避障仿真(Matlab代码实现)
【无人机】无人机群在三维环境中的碰撞和静态避障仿真(Matlab代码实现)
390 0
|
NoSQL Redis
redis使用jackson序列化数据配置文件
redis使用jackson序列化数据配置文件
376 5
|
Kubernetes Devops 持续交付
DevOps和kubernetes概述
DevOps和kubernetes概述
|
存储 安全 物联网
探索未来网络:物联网安全的挑战与对策
本文深入探讨了物联网(IoT)技术的基本概念、发展现状以及面临的主要安全挑战,并提出了相应的解决策略。通过对当前物联网设备的安全漏洞和攻击手段的分析,文章强调了加强设备认证、数据加密和隐私保护等措施的重要性。同时,呼吁业界共同努力,制定统一的安全标准和规范,以促进物联网技术的健康发展。
|
JSON Go 数据格式
langchain 入门指南 - 让 LLM 自动选择不同的 Prompt
langchain 入门指南 - 让 LLM 自动选择不同的 Prompt
651 0
|
安全 Docker 容器
dockercompose如何配置特权启动
dockercompose如何配置特权启动
|
JSON 数据格式
FileBeat替换@timestamp的四种方法
FileBeat替换@timestamp的四种方法
1614 0
|
弹性计算 安全 虚拟化
万字干货分享 | 阿里云CIPU技术解析
2022年6月,阿里云发布了云基础设施处理器CIPU(Cloud  Infrastructure Processing  Unit),将其定义为取代传统CPU的新一代云计算体系架构的核心。在这个全新体系架构下,CIPU向下对数据中心计算、存储、网络等底层基础设施快速云化并进行硬件加速,向上接入飞天云操作系统,将全球数百万台服务器构建为一台超级计算机,实现资源的灵活编排和调度,给用户提供高质量弹性云计算算力集群。
万字干货分享 | 阿里云CIPU技术解析

热门文章

最新文章