【发布时间】:2018-08-16 05:32:29
【问题描述】:
我正在尝试这个:
import pandas as pd
import sqlite3
import datetime, pytz
#nowtime=datetime.datetime.now(pytz.utc)
nowtime=datetime.datetime.now()
print(nowtime)
df = pd.DataFrame(columns=list('ABCD'))
df.loc[0]=(3,0.141,"five-nine",nowtime)
df.loc[1]=(1,0.41,"four-two",nowtime)
print(df)
db = sqlite3.connect(':memory:')
c = db.cursor()
c.execute('create table if not exists ABCD ( A integer, B real, C text, D timestamp );')
c.execute('insert into ABCD (A,B,C, D) values (?,?,?,?);',(1,2.2,'4',nowtime))
c.executemany('insert into ABCD (A,B,C, D) values (?,?,?,?);',df.to_records(index=False))
db.commit()
print(pd.read_sql('select * from ABCD;',db))
得到这个:
2018-03-07 19:09:58.584953
A B C D
0 3 0.141 five-nine 2018-03-07 19:09:58.584953
1 1 0.410 four-two 2018-03-07 19:09:58.584953
A B C D
0 1 2.200 4 2018-03-07 19:09:58.584953
1 3 0.141 five-nine b'\xa8hx?\t\xb9\x19\x15'
2 1 0.410 four-two b'\xa8hx?\t\xb9\x19\x15'
理想情况下,我想将一些带有时间戳的数据推送到 sqlite3 中,并以可互操作的方式将其恢复回 pandas/python/numpy。
我已经看到 Appending Pandas dataframe to sqlite table by primary key 用于追加,但我不确定如何使用 sqlite3 使用 datetime.datetime、pandas Timestamps 或 numpy.datetime64 次。
此外,还有 How to read datetime back from sqlite as a datetime instead of string in Python?,但我不知道如何在 pandas 中做到这一点。
我花了很多时间在https://stackoverflow.com/a/21916253/1653571 和令人困惑的多个 to_datetime()s 上。
使用 times、sqlite3 和 pandas 的好方法是什么?
####### 更新:我尝试了这些更改:
db = sqlite3.connect(':memory:',detect_types=sqlite3.PARSE_DECLTYPES)
#...
for index,row in df.iterrows():
print(row)
c.execute('insert into ABCD (A,B,C,D) values (?,?,?,?);',(row.A,row.B,row.C,row.D.to_pydatetime()))
x = pd.read_sql('select * from ABCD;',db)
print('Type of a pd.read_sql(SQLite3) timestamp : ',type(x['D'][0]))
x = c.execute('select * from ABCD').fetchall()
print(x)
print('Type of a sqlite.execute(SQLite3) timestamp : ',type(x[0][3]))
使用 SQLite3 数据类型并测试返回值:
Type of a pd.read_sql(SQLite3) timestamp : <class 'pandas._libs.tslib.Timestamp'>
[(1, 2.2, '4', datetime.datetime(2018, 3, 8, 14, 46, 2, 520333)), (3, 141.0, 'five-nine', datetime.datetime(2018, 3, 8, 14, 46, 2, 520333)), (1, 41.0, 'four-two', datetime.datetime(2018, 3, 8, 14, 46, 2, 520333))]
Type of a sqlite.execute(SQLite3) timestamp : <class 'datetime.datetime'>
另外,当我尝试datetime.datetime.now(pytz.utc) 来获取 UTC 感知时间时,它破坏了很多东西。使用 datetime.datetime.utcnow() 通过返回不受时区影响的非时区感知对象效果更好。
还要注意关于sqlite3.connect(detect_types=...) 参数的Python sqlite3 文档。启用detect_types=PARSE_DECLTYPES|PARSE_COLNAMES 提示 python 对系统之间传递的数据运行转换器。
-
https://docs.python.org/3/library/sqlite3.html#sqlite3.PARSE_DECLTYPES 用于
create table ... xyzzy timestamp, ...转化 -
https://docs.python.org/3/library/sqlite3.html#sqlite3.PARSE_COLNAMES 用于
select ... date as "dateparsed [datetime]"...转换
【问题讨论】:
标签: python pandas datetime sqlite timestamp