2012-02-09 93 views
3

我有一個奇怪的問題,在Python 2.7中的sqlite3日期時間對象。運行這個例子:sqlite3中的Python日期時間

import sqlite3 
import datetime 

con = sqlite3.connect(":memory:", detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES) 
cur = con.cursor() 
cur.execute("create table test(d date, ts timestamp)") 

today = datetime.date.today() 
now = datetime.datetime.now() 

cur.execute("insert into test(d, ts) values (?, ?)", (today, now)) 
cur.execute("select d, ts from test") 
row = cur.fetchone() 
print today, "=>", row[0], type(row[0]) 
print now, "=>", row[1], type(row[1]) 

cur.execute('select current_date as "d [date]", current_timestamp as "ts [timestamp]"') 
row = cur.fetchone() 
print today, "=>", row[0], type(row[0]) 
print now, "=>", row[1], type(row[1]) 

給了我這樣的輸出:

2012-02-10 => 2012-02-10 <type 'datetime.date'> 
2012-02-10 08:17:10.222291 => 2012-02-10 08:17:10.222291 <type 'datetime.datetime'> 
2012-02-10 => 2012-02-09 <type 'datetime.date'> 
2012-02-10 08:17:10.222291 => 2012-02-09 19:17:10 <type 'datetime.datetime'> 

日期時間時,使用PARSE_COLNAMES方法似乎是錯誤的retrived。這是爲什麼?

注意這個例子是從Python docs

回答

2

從你的顯示輸出,它看起來像你在新西蘭時區(UTC-12或UTC-11日光節約時間被觀察到的)。問題是PARSE_COLNAMES如何使用轉換器的python類型 - 一個是UTC,一個是使用本地時間可用的時區信息(和,是的,我會稱這是一個轉換器中的錯誤)。

見我用股票價格數據饋送到持續轉換數據,我知道(你可以調整它以符合您的時區,或添加一些代碼調整爲檢測時區)時區適配器下面:

def adapt_datetime(dt): 
    # Get the datetime for the POSIX epoch. 
    epoch = datetime.datetime.utcfromtimestamp(0.0) 
    elapsedtime = dt - epoch 
    # Calculate the number of milliseconds. 
    seconds = float(elapsedtime.days)*24.*60.*60. + float(elapsedtime.seconds) + float(elapsedtime.microseconds)/1000000.0 
    return seconds 


def convert_datetime(tf): 
    # Note: strange math is used to account for daylight savings time and 
    # times in the Eastern (US) time zone (e.g. EDT) 
    tf = float(tf) 
    edt_adjustment = 6 * 60. * 60. 
    if time.localtime(tf).tm_isdst: 
     edt_adjustment = 5 * 60. * 60. 
    return datetime.datetime.fromtimestamp(tf+edt_adjustment) 

sqlite3.register_adapter(datetime.datetime, adapt_datetime) 
sqlite3.register_converter("datetime", convert_datetime) 

您可能會在github上的this bit of code中看到所有這些。

+0

謝謝你的清理,是一個真正的頭部劃痕 – pearpenguin 2012-02-09 21:56:20