EMP*_*EMP 62 python sqlite datetime
我正在使用Python 2.6.4中的sqlite3模块在SQLite数据库中存储日期时间.插入它非常简单,因为sqlite会自动将日期转换为字符串.问题是,当它读取它时它会以字符串形式返回,但我需要重建原始日期时间对象.我该怎么做呢?
Ale*_*lli 106
如果您使用时间戳类型声明列,则表示您处于三叶草中:
>>> db = sqlite3.connect(':memory:', detect_types=sqlite3.PARSE_DECLTYPES)
>>> c = db.cursor()
>>> c.execute('create table foo (bar integer, baz timestamp)')
<sqlite3.Cursor object at 0x40fc50>
>>> c.execute('insert into foo values(?, ?)', (23, datetime.datetime.now()))
<sqlite3.Cursor object at 0x40fc50>
>>> c.execute('select * from foo')
<sqlite3.Cursor object at 0x40fc50>
>>> c.fetchall()
[(23, datetime.datetime(2009, 12, 1, 19, 31, 1, 40113))]
Run Code Online (Sandbox Code Playgroud)
看到?int(对于声明为整数的列)和datetime(对于声明为timestamp的列)都存活,并且类型完好无损.
EMP*_*EMP 21
事实证明,sqlite3可以做到这一点,它甚至可以记录,但它很容易错过或误解.
我必须做的是:
Run Code Online (Sandbox Code Playgroud)conn = sqlite3.connect(dbFilePath, detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES)
将我想要的类型放入查询 - 对于datetime,它实际上不是"datetime",而是"timestamp":
sql = 'SELECT jobid, startedTime as "[timestamp]" FROM job'
cursor = conn.cursor()
try:
cursor.execute(sql)
return cursor.fetchall()
finally:
cursor.close()
Run Code Online (Sandbox Code Playgroud)如果我传入"datetime"而不是它被默默地忽略,我仍然得到一个字符串.如果我省略引号则相同.
| 归档时间: |
|
| 查看次数: |
46207 次 |
| 最近记录: |