我在我的脚本中看到了最奇怪的行为。我从 dbapi2.py 收到 ValueError,它似乎试图对 datetime.date 对象进行转换,就好像它是 datetime.datetime 对象一样:
File "C:\Python27\Lib\sqlite3\dbapi2.py", line 66, in convert_timestamp
datepart, timepart = val.split(" ")
ValueError: need more than 1 value to unpack
我没有做任何特别的事情,事实上我有几个其他脚本用稍微不同的 tSql 做完全相同的事情,并且没有任何问题。这是构建 Sql 的类:
class TransactionQuery:
def __init__(self, account_iter, date):
self.account_iter = tuple(account_list)
self.date = date
placeholder = ("?" for item in self.account_list)
placeholders = ', '.join(item for item in placeholder)
self.query = """select * from transactions where account_cd in (%s) and
effected_dt = ?""" % placeholders
@property
def params(self):
return (self.account_list) + (self.date,)
调用它的代码:
with Sqlite() as curs:
print mquery.query
print mquery.params
curs.execute(mquery.query, mquery.params)
return curs.fetchall()
打印语句的输出:
select * from transactions where account_cd in (?, ?, ?, ?) and effected_dt = ?
('713271', '71204', '713311', '713471', datetime.date(2012, 12, 17))
在这种情况下,你知道为什么 Sqlite 会遇到 datetime.date 对象的问题吗?
最佳答案
您缺少时间部分
:
(datepart, timepart) = str( datetime.date(2012, 12, 17) ).split( ' ' )
## ValueError: need more than 1 value to unpack
sqlite3
正在点击 convert_timestamp
转换器。
Default Adapters and Converters sqlite3
的文档页面显示了一些示例。根据已知的信息,我可以尝试假设 effected_dt
是一个 timestamp
,它需要一个完整的 datetime.datetime
字符串。
因此,您需要执行以下操作:
- 改用
datetime.datetime
- 为接受日期的
timestamp
类型注册一个新转换器(例如返回“2012-12-17 00:00:00”) - 更改列类型
希望这是有意义的并且有帮助。
关于python - Sqlite3 dbapi2.py 日期转换问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13932380/