我是一名新手编码器,所以请保持温柔。我试图将一个时间戳类型的日期列从Postgres 9数据库(日期在数据库中看起来像这样:2012-03-02 14:25:49)放入rpy2向量中(我使用rpy2)版本2.3.9)然后可以使用ggplot2为图表创建DataFrame。似乎POSIXlt是适当的rpy2数据类型,但也许我错了。我不需要时间,只需要图表的日期。我在Python 2.7中这样做,使用SqlAlchemy 8.3访问数据库的日期列,SQLAlchemy将其转换为Python datetime.datetime格式。日期数据位于" publish_date'列/代码如下。连接和访问数据库似乎工作正常,所以我认为这主要是一个rpy2问题。这是代码:
# PART 0 - Initialize the packages
import sqlalchemy
from sqlalchemy import *
import rpy2.robjects as robjects
from rpy2.robjects.vectors import DataFrame
from rpy2.robjects.packages import importr
import rpy2.robjects.lib.ggplot2 as ggplot2
# PART 1 - connect to the database
engine = create_engine('postgresql://postgres:pword@localhost/mydb')
metadata = MetaData()
conn = engine.connect()
# PART 2 - ask for stories table
stories = Table('stories', metadata, autoload=True, autoload_with=engine)
# PART 3 - read from that table and populate a new dictionary
select = sqlalchemy.sql.select
# create dictionary with column names as keys and empty lists of vectors for data
newdict = {
"stories_id":robjects.IntVector([]),
"publish_date":robjects.POSIXlt([])
}
# connect to the database, execute a SELECT statement that iterates through table
# populate the cursor 'row' with data from the table
for row in conn.execute(select([Table('stories', metadata, autoload=True autoload_with=engine)])):
newdict["stories_id"] += row.stories_id
newdict["publish_date"] += row.publish_date
这是我到目前为止运行代码时遇到的错误。
ValueError Traceback (most recent call last)
<ipython-input-377-4483b6760461> in <module>()
50 for row in conn.execute(select([Table('stories', metadata, autoload=True, autoload_with=engine)])):
51 newdict["stories_id"] += row.stories_id
---> 52 newdict["publish_date"] += row.publish_date
53
54
/Users/user/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/rpy2-2.3.9- py2.7-macosx-10.6-x86_64.egg/rpy2/robjects/vectors.pyc in __add__(self, x)
226
227 def __add__(self, x):
--> 228 res = baseenv_ri.get("c")(self, conversion.py2ri(x))
229 res = conversion.ri2py(res)
230 return res
/Users/user/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/rpy2-2.3.9- py2.7-macosx-10.6-x86_64.egg/rpy2/robjects/numpy2ri.pyc in numpy2ri(o)
59 raise(ValueError("Unknown numpy array type."))
60 else:
---> 61 res = ro.default_py2ri(o)
62 return res
63
/Users/user/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/rpy2-2.3.9- py2.7-macosx-10.6-x86_64.egg/rpy2/robjects/__init__.pyc in default_py2ri(o)
146 res = rinterface.SexpVector([o, ], rinterface.CPLXSXP)
147 else:
--> 148 raise(ValueError("Nothing can be done for the type %s at the moment." % (type(o))))
149 return res
150
ValueError: Nothing can be done for the type <type 'datetime.datetime'> at the moment.
谢谢您提供的任何帮助。我完全失去了。