pythonrrpy2

How to pass a date to R from Python using rpy2


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


Solution

  • 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"