Search code examples
rdatetimexts

How to convert numeric time into date, time format in R


Trying to build an xts for my data. The date fromat it okay but I dont know how to convert "time" column into a time format. Time is stored as numeric, the data looks like:

      date time  price
1 19900102  930 353.40
2 19900102  931 353.25
3 19900102  932 353.02
4 19900102  933 352.97
5 19900102  934 352.81
6 19900102  935 352.74

I tried the following code but it doesnt work.

sp500.xts <-  as.xts(sp500[,3],order.by=as.POSIXct(strptime(paste(as.character(sp500[,1]),as.character(sp500[,2])),"%Y%m%d %H:%M")))

Thanks for anyone who helps.


Solution

  • Big fan of parse_date_time from lubridate and the timetk package:

    library(tidyverse)
    library(lubridate)
    library(timetk)
    
    test %>%
      mutate(date = parse_date_time(paste(date, str_pad(time, 4, side = "left", pad = "0")), "YmdHM")) %>%
      select(-time) %>%
      tk_xts(silent = T)
    
                         price
    1990-01-02 09:30:00 353.40
    1990-01-02 09:31:00 353.25
    1990-01-02 09:32:00 353.02
    1990-01-02 09:33:00 352.97
    1990-01-02 09:34:00 352.81
    1990-01-02 09:35:00 352.74