Date to float from an R Tibble in Python

Viewed 176

By using an API, I retrieved a Tibble (an R object) in Python (using rpy2.objects), that is a very large 2-dimensional table. It contains a column with dates in the format "YYYY-MM-DD" when I print the Tibble object. When I grab the Date in Python (simply by indexing the Tibble) it is converted to a 5 digit float. For example, the date "2019-09-28" is converted to the float 18167.0. I'm not sure how to convert it back to a string date (e.g. "YYYY-MM-DD").

Does anyone have any ideas? I'm happy to clarify anything that I can :)

Edit: The answer I discovered with help was the following

import pandas as pd
pd.to_datetime(18167.0,unit='d',origin='1970-01-01')
1 Answers

If the Date class got converted to numeric storage mode, we can use as.Date with origin

as.Date(18167, origin = "1970-01-01")
#[1] "2019-09-28"

The Date storage mode is numeric

storage.mode(Sys.Date())
#[1] "double"

In python, we can also do

from datetime import datetime, date, time
date.fromordinal(int(18167) + date(1970, 1, 1).toordinal()).strftime("%Y-%m-%d")
#'2019-09-28'
Related