将日期时间插入SQLite数据库 [英] Inserting datetime into a SQLite Database

查看:141
本文介绍了将日期时间插入SQLite数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将时间插入数据库,但是当我打印插入的内容时,这是不正确的。我在将时间变量插入数据库之前打印了时间变量,它是 12:01:09.149059。当我使用 strftime 时,它工作正常,但由于时间已到,所以切换了。

I am trying to insert the time into my database but when I print what I inserted it isn't correct. I printed the time variable before inserting it into the database and it is "12:01:09.149059". It was working fine when I was using strftime but I switched because the time was off.

from datetime import datetime
time = str(datetime.now().time())
cur.execute("insert into apple values (?,?,?)",(price,time,date))
con.commit()

#prints:
>>>('132.75', "<method 'time' of 'datetime.datetime' objects>", 'Apr 27, 2015')


推荐答案

您正在尝试将Python方法对象转换为字符串,该字符串默认为您不需要的表示形式。尝试以下操作:

You are trying to convert a Python method object into a string, which is defaulting to its representation, which you don't want. Try this instead:

from datetime import datetime
time = datetime.now().strftime("%B %d, %Y %I:%M%p")
cur.execute("insert into apple values (?,?,?)",(price,time,date))
con.commit()

#prints:
>>>('132.75', "Apr 27, 2015 09:38AM", 'Apr 27, 2015')

这篇关于将日期时间插入SQLite数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆