Search code examples
rexceldatetime-seriesfinance

How do I keep the date-format from Excel when importing a time series in R?


When I import a financial time series from Excel to R, the dates turn into integers. Each column represents a date. I understand that Excel converted them to a form where they represent the number of days since the origin date of 01/01/1900. How can I turn these numbers back into 'normal' dates in R?


Solution

  • I would use one of these functions:

    xlsnum_to_POSIXct <- function(n)
    {
        as.POSIXct(
           x = n*24*60*60,
           origin = "1900-01-01 00:00:00"
        );
    }
    
    xlsnum_to_POSIXlt <- function(n)
    {
        as.POSIXlt(
           x = n*24*60*60,
           origin = "1900-01-01 00:00:00"
        );
    }
    

    which converts the number of days into number of seconds since 1900/01/01, and wraps it conveniently into an R date-time type.

    Should work also with fractions of day, vectors of day counts etc.