Michael Mo
Michael Mo

Reputation: 23

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.

Upvotes: 0

Views: 496

Answers (2)

tomasu
tomasu

Reputation: 1438

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

Upvotes: 0

liuminzhao
liuminzhao

Reputation: 2455

Assuming 930 = 09:30, may try this:

timec is to pad to get the full hm; dtc is to get the full date time, then use ymd_hm to read into datetime format.

library(tidyverse)

library(lubridate)


test %>% 
  mutate(timec = str_pad(time, 4, side = 'left', pad = '0'),
         dtc = str_c(date, timec),
         dt = ymd_hm(dtc))

> test %>% 
+   mutate(timec = str_pad(time, 4, side = 'left', pad = '0'),
+          dtc = str_c(date, timec),
+          dt = ymd_hm(dtc))
      date time  price timec          dtc                  dt
1 19900102  930 353.40  0930 199001020930 1990-01-02 09:30:00
2 19900102  931 353.25  0931 199001020931 1990-01-02 09:31:00
3 19900102  932 353.02  0932 199001020932 1990-01-02 09:32:00
4 19900102  933 352.97  0933 199001020933 1990-01-02 09:33:00
5 19900102  934 352.81  0934 199001020934 1990-01-02 09:34:00
6 19900102  935 352.74  0935 199001020935 1990-01-02 09:35:00

Upvotes: 1

Related Questions