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', '', 2, 36, 23, 43, 12, 25, 29),
('2016-01-03', '', 34, 35, 17, 49, 24, 30, 16),
('2016-01-05', '', 1, 35, 12, 49, 49, 26, 34),
('2016-01-08', '', 6, 35, 10, 40, 4, 23, 2),
('2016-01-10', '', 14, 35, 27, 40, 4, 12, 45),
('2016-01-12', '', 33, 10, 13, 21, 27, 22, 17),
('2016-01-15', '', 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', '', 2, 36, 23, 43, 12, 25, 29),
('2016/1/3', '', 34, 35, 17, 49, 24, 30, 16),
('2016/1/5', '', 1, 35, 12, 49, 49, 26, 34),
('2016/1/8', '', 6, 35, 10, 40, 4, 23, 2),
('2016/1/10', '', 14, 35, 27, 40, 4, 12, 45),
('2016/1/12', '', 33, 10, 13, 21, 27, 22, 17),
('2016/1/15', '', 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)
sqlite3日期数据类型的更多相关文章
- SQL2008 的 日期数据类型
摘要 你是否曾经想在数据库中存储一个日期而没有时间部分,或者想存储一个时间值希望有更高的精度?在SQL Server 2008的介绍中,微软介绍了一些新的日期数据类允许你只存储一个日期.更高精度的时间 ...
- MySQL日期数据类型、时间类型使用总结
MySQL日期数据类型.时间类型使用总结 MySQL日期数据类型.MySQL时间类型使用总结,需要的朋友可以参考下. MySQL 日期类型:日期格式.所占存储空间.日期范围 比较. 日期类型 ...
- MySQL日期数据类型、MySQL时间类型使用总结
MySQL:MySQL日期数据类型.MySQL时间类型使用总结 MySQL 日期类型:日期格式.所占存储空间.日期范围 比较. 日期类型 存储空间 日期格式 日期范围 ------------ --- ...
- SQLite3日期与时间,常见函数
SQLite3日期与时间,常见函数 import sqlite3 #con = sqlite3.connect('example.db') con = sqlite3.connect(":m ...
- MySQL日期数据类型总结
MySQL:MySQL日期数据类型.MySQL时间类型使用总结 MySQL 日期类型:日期格式.所占存储空间.日期范围 比较. 日期类型 存储空间 日期格式 ...
- MySQL日期数据类型和时间类型使用总结
转自: http://blog.chinaunix.net/space.php?uid=11327712&do=blog&id=32416 MySQL 日期类型:日期格式.所占存储空间 ...
- MySQL:MySQL日期数据类型、MySQL时间类型使用总结
MySQL 日期类型:日期格式.所占存储空间.日期范围 比较. 日期类型 存储空间 日期格式 日期范围------------ -------- ...
- Oracle中的日期数据类型
TimeStamp日期类型 TimeStamp数据类型用于存储日期的年.月.日,以及时间的小时.分和秒,其中秒值精确到小数点后6位,该数据类型 同时包含时区信息.systimestamp函数的功能是返 ...
- POI处理Excel中的日期数据类型
在POI处理Excel中的日期类型的单元格时,如果仅仅是判断它是否为日期类型的话,最终会以NUMERIC类型来处理. 正确的处理方法是先判断单元格 的类型是否则NUMERIC类型, 然后再判断单元格是 ...
随机推荐
- 四级菜单实现(Python)
menu_dict = { '山东' : { '青岛' : { '四方':{'兴隆路','平安路','杭州路'}, '黄岛':{}, '崂山':{} }, '济南' : { '历城':{}, '槐荫' ...
- asp,mdb,工具
<%set conn=Server.CreateObject("ADODB.Connection")conn.Provider="Microsoft.Jet.OLE ...
- 【[HNOI2004]敲砖块】
非常巧妙的\(dp\)顺序 这道题如果按照最正常的顺序来\(dp\)的话,显然是没有办法做的,后效性太大了 所以我们可以巧妙的改变\(dp\)的顺序 我们注意到一个位置\((i,j)\)要被打到的话就 ...
- MVC渲染文章内容的html标签转义
文章详情页一般从数据库中取出文章内容,文章内容一般含有 等html标签,MVC中如果直接从模型输出文章内容,会把html标签转义变成<>等,这时候是要把转义后的标签变成html标签, ...
- ethereumjs-vm/examples/run-transactions-simple
https://github.com/ethereumjs/ethereumjs-vm/tree/master/examples/run-transactions-simple prerequisit ...
- iOS获取当前连接的wifi信息
导入框架CaptiveNetwork #import <SystemConfiguration/CaptiveNetwork.h> 获取当前连接的wifi信息 // 只能获取当前的SSID ...
- ActiveRecord初始化,可以实现jfinal系统启动完成后,再建立数据库连接
1.JFinalConfig的afterJFinalStart方法,可以实现系统启动成功后,调用的方法 2.ActiveRecord 多数据源初始化 package com.meiah.common; ...
- 如何快速找到指定端口被哪个程序占用并释放该端口(解决bindException)
首先打开打开任务管理器,选择性能模块,下方有打开资源监视器,或者直接搜索资源监视器 在资源监视器中点击侦听端口模块,即可看到正在使用网络端口的应用程序名和pid,如果被占用可以直接使用命令行关闭即可 ...
- ios开发遇到的问题
运行后界面空白,Xcode跳转到APPDelegate.swift文件提示如下 第一种可能原因: 做输出口后在代码中重新命名了输出口 解决方法: 右键控件关闭输出口的连接,变回+号,将它重新连到代码的 ...
- LL(1)文法--递归下降程序
递归下降程序 递归下降程序一般是针对某一个文法的.而递归下降的预测分析是为每一个非终结符号写一个分析过程,由于文法本身是递归的,所以这些过程也是递归的. 以上是前提. Sample 假如给的是正规式子 ...