Search code examples
rdataframexts

Converting date and hour into xts R


i have this table of consumptions. I am trying to convert the first two columns into a one xts date format.

1   01.01.2016  00:00:00    26.27724
2   01.01.2016  01:00:00    24.99182
3   01.01.2016  02:00:00    23.53261
4   01.01.2016  03:00:00    22.46478
5   01.01.2016  04:00:00    22.00291
6   01.01.2016  05:00:00    21.95708
7   01.01.2016  06:00:00    22.20354
8   01.01.2016  07:00:00    21.84416

i have tried the code belo and got that error.

timestamp=format(as.POSIXct(paste(datecol,hourcol)), "%d/%m/%Y %H:%M:%S")

Error in as.POSIXlt.character(x, tz, ...) : character string is not in a standard unambiguous format

the date is character and hour is in double format.


Solution

  • If you were trying to combine date and time value to create timestamp, we can use as.POSIXct in base R.

    df$timestamp <- as.POSIXct(paste(df$datecol,df$hourcol), 
                              format = "%d.%m.%Y %T", tz = "UTC")
    

    Or using lubridate

    df$timestamp <- lubridate::dmy_hms(paste(df$datecol,df$hourcol))
    

    Or using anytime

    df$timestamp <- anytime::anytime(paste(df$datecol,df$hourcol))