How to pass a date to R from Python using rpy2

Question:

I want to call a function from R which requires a Date object. I’m struggling to call this function using Rpy2.

Here’s an example: An R function that takes a date

d <- as.Date("2009-08-17")
format(d, "%d/%m/%Y")
[1] "17/08/2009"

Now I want to call this function from python

import datetime as dt
import rpy2.robjects.packages as rpackages
base = rpackages.importr("base") 
d = dt.date(year=2009, month=8, day=17)
base.format(d, format = "%d/%m/%y")

The last line throws the exception

NotImplementedError: Conversion 'py2ri' not defined for objects of type    '<class 'datetime.datetime'>'

Any ideas how I can pass dates from python to function in R expecting as.Date(xxx) arguments?

fyi – I’m not looking for pure python code to convert the format of the date string. I want to know how to pass dates via rpy2

Asked By: mark

||

Answers:

Currently, you are not running the as.Date() function, translated as base.as_Date(). Consider doing so and then formatting to string. But first format the Python datetime object to string with strfttime:

import datetime as dt
import rpy2.robjects.packages as rpackages
import rpy2.robjects as robjects

base = rpackages.importr("base") 
pyDate = dt.date(year=2009, month=8, day=17)

rDate = base.as_Date(pyDate.strftime("%Y-%m-%d"))
rStr = base.format(rDate, format = "%d/%m/%Y")

print(robjects.StrVector(rStr).r_repr())
# "17/08/2009"
Answered By: Parfait
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.