![](/img/trans.png)
[英][TypeError: can't compare datetime.datetime to tuple]: How to compare a tuple value to a datetime value using Python & SQLite3?
[英]sqlite3 datetime.datetime python select
sqlite3數據庫有成千上萬的行。 我想按(datetime.datetime(now))
對列進行排序
該表可能是:
c.execute(“CREATE TABLE IF NOT EXISTS table_one (time_column TEXT,column_two REAL,column_three REAL)”)
time
欄為TEXT
插入效果很好,我有成千上萬的行。 我需要按時間查看數據。 例如,“ 2019年1月3日凌晨1:00和凌晨2:00之間的平均偏差和標准偏差是多少”(大約300個數字)
像這樣:
all_rows = c.execute('SELECT column_two FROM table_one WHERE time_column > 2019-01-03 01:00:00:000000 and time_column < 2019-01-03 02:00:00:000000 ‘)
fetchall
需要進入數組進行統計分析,但這是另一個問題。
目前,可以檢索datetime
時間。 它以unicode
(無論是unicode
形式)
但是我需要使用datetime
字段進行決策。 TEXT
有問題嗎? 我可以添加一列,然后將date stamp
更改為“ unix時間戳”,這似乎是一個海峽數字。
我正在學習越來越多的東西,但是堅持下去……。 幫助(謝謝)
您實質上是在尋求有關如何設計數據庫以提高某些請求效率的建議。 可能范圍很廣,但是我將嘗試這個簡單的例子。
首先(也是您的問題),對於沒有專用日期類型的SQLite,時間列的TEXT
類型是可接受的。 日期將轉換為ISO8601字符串(“ YYYY-MM-DD HH:MM:SS.SSS”),以確保與比較運算符兼容。 要問的好問題是日期值的范圍是多少,以及是否需要評估日期差。 如果您只需要一秒的精度且日期大於1970-01-01,則INTEGER(自1970-01-01 00:00:00 UTC以來的秒數)很好,而REAL(Julian天數)如果滿足精確的精度無關緊要(因為浮點數不准確),但是需要很大的范圍。
但是,對於查詢效率而言最重要的是索引的存在。 因此,如果您需要使用time_column
改進查詢,請在其上聲明一個索引。 您的代碼可能變為:
c.execute("CREATE TABLE IF NOT EXISTS table_one (time_column TEXT,column_two REAL,"
"column_three REAL)")
c.execute("CREATE INDEX IF NOT EXISTS index_time_table_one ON table_one(time_column)")
選擇部分將是:
curs = c.execute("SELECT column_two FROM table_one WHERE time_column"
"BETWEEN '2019-01-03 01:00:00' and '2019-01-03 02:00:00'")
這樣一來,在獲取time_column
列時,您將獲得ISO字符串表示形式。
Python SQLite3模塊甚至可以更智能地顯示日期,並且可以自動將它們轉換為時間戳,只要您提出以下要求即可:
# declare that you want to use custom datatypes, declare in columns
c = sqlite3.connect('your_db', detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES)
# declare the time_column to be a timestamp:
c.execute("CREATE TABLE IF NOT EXISTS table_one (time_column timestamp,column_two REAL,"
"column_three REAL)")
# declare the index
c.execute("CREATE INDEX IF NOT EXISTS index_time_table_one ON table_one(time_column)")
填充數據庫后,您可以照常獲取它並直接檢索Python datetime對象:
curs = c.execute("SELECT * FROM table_one WHERE time_column BETWEEN"
" '2019-01-03 01:00:00' and '2019-01-03 02:00:00'")
r = curs.fetchone()
print(r)
將輸出:
(datetime.datetime(2019, 1, 2, 0, 0), ...)
缺點是不再是標准SQL,如果您使用其他數據庫,則需要進行調整。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.