omzeybek omzeybek - 3 years ago 143
R Question

Creating a date/time object by two string objects

I have two objects named "Date" and "Time". The date is in YYYY.mm.dd and time is in HH:MM format. I need to create a date and time object for my financial econometrics assignment.

First I paste two objects together and create a character vector such like following:

Date Time Open High Low
1 2017.09.01 00:00 1.19013 1.19017 1.19013
2 2017.09.01 00:01 1.19015 1.19017 1.19015


However, when I tried to convert "date_time_c" character vector to "POSIXct" format, I used the following code.

DATA<-DAT%>%select(Date,Time,Open,High,Low)%>%
mutate(Date_Time=as.POSIXct(paste(DATA$Date, DATA$Time), format="%YYYY.%mm.%dd %H:%M"))


but as a result, I am receiving "null" values when checked newly created "Date_Time" object

> head(DATA$Date_Time)
[1] NA NA NA NA NA NA


Should I first cast my character vector integers?? I am not sure..

Can anyone help me on this error

Answer Source

You can also use the lubridate package (part of the Tidyverse) that has functions to convert strings to date or date-time objects using the functions like ymd_hm().

library(tidyverse)
library(lubridate)

df <- tribble(~Date,  ~Time,  ~Open,  ~High,  ~Low,
"2017.09.01", "00:00", "1.19013", "1.19017", "1.19013",   
"2017.09.01", "00:01", "1.19015", "1.19017", "1.19015")

df %>% mutate(Date.Time = ymd_hm(paste(Date, Time, sep=" ")))

which produces

# A tibble: 2 x 6
        Date  Time    Open    High     Low           Date.Time
       <chr> <chr>   <chr>   <chr>   <chr>              <dttm>
1 2017.09.01 00:00 1.19013 1.19017 1.19013 2017-09-01 00:00:00
2 2017.09.01 00:01 1.19015 1.19017 1.19015 2017-09-01 00:01:00
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download