sqlite3中的Python日期时间

时间:2012-02-09 19:28:11

标签: python sqlite

我在Python 2.7中对sqlite3 datetime对象有一个奇怪的问题。运行此示例:

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方法时重试的日期时间似乎是错误的。那是为什么?

请注意,此示例来自Python docs

1 个答案:

答案 0 :(得分: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中看到所有这些内容。