为什么datetime
类型在将它们插入Sqlite数据库后会丢失?
import sqlite3, datetime
dbconn = sqlite3.connect(':memory:')
c = dbconn.cursor()
c.execute('create table mytable(title text, t timestamp)')
c.execute('insert into mytable (title, t) values (?, ?)', ("hello2", datetime.datetime(2018,3,10,12,12,00)))
c.execute("select * from mytable")
for a in c.fetchall():
print a[0] # hello2
print type(a[0]) # <type 'unicode'>
print a[1] # 2018-03-10 12:12:00
print type(a[1]) # <type 'unicode'>
插入和查询后,日期时间类型是否仍然存在?
PS:由于这个问题,我失去了将近一个小时,所以我现在将回答“回答你自己的问题 - 分享你的知识,Q&amp; A风格”的SO功能。注意:这不是this neighbour question的副本,因为它没有涉及如何存储/检索日期时间。
答案 0 :(得分:0)
根据this documentation,解决方案是使用detect_types
参数:
dbconn = sqlite3.connect(':memory:', detect_types=sqlite3.PARSE_DECLTYPES)
然后前面代码的输出将是:
hello2
<type 'unicode'>
2018-03-10 12:12:00
<type 'datetime.datetime'>
还有this is an important note关于Sqlite中的日期时间:
SQLite没有预留用于存储日期和/或时间的存储类。相反,SQLite的内置日期和时间函数能够将日期和时间存储为TEXT,REAL或INTEGER值:
- TEXT as ISO8601 strings(“YYYY-MM-DD HH:MM:SS.SSS”)。
- 真实的朱利安日数,即公元前4714年11月24日格林威治中午以来的天数。根据公历格里高利历。
- INTEGER as Unix Time,自1970-01-01 00:00:00 UTC以来的秒数。
应用程序可以选择以任何格式存储日期和时间,并使用内置的日期和时间函数在格式之间自由转换。
答案 1 :(得分:0)
要求用户输入日期时间:(例如,&#39; 2005年6月1日1:33 PM&#39;)
date_entry = input('Enter a date in YYYY-MM-DD h:m am/pm format')
将其转换为日期时间对象:
date1 = datetime.strptime(date_entry, '%b %d %Y %I:%M%p')
to inter to sql table:
insert table1 (dateField)
values (convert(datetime,date1,5));
如果您在从sql读取后再次需要转换
datetime_object = datetime.strptime(dateField, '%b %d %Y %I:%M%p')