Search code examples
rdatecharacterintervals

splitting Interval Date in character and casting into Date in R


I have below Date column in character (from ENTSO-E platform). I want to convert into Date and extract the end part of this Interval ([1] "01.01.2021 00:00 - 01.01.2021 01:00"). I am receiving error "character string in unambiguous format". Any suggestions how can I extract the second part of the interval that is in character format to a Date variable in R?

head(date)
  • "01.01.2021 00:00 - 01.01.2021 01:00"
  • "01.01.2021 01:00 - 01.01.2021 02:00"
  • "01.01.2021 02:00 - 01.01.2021 03:00"
  • "01.01.2021 03:00 - 01.01.2021 04:00"
  • "01.01.2021 04:00 - 01.01.2021 05:00"
  • "01.01.2021 05:00 - 01.01.2021 06:00"
Error in as.POSIXlt.character(x, tz, ...) : 
  character string is not in a standard unambiguous format

Solution

  • as.POSIXct(gsub("^.* - (.*)", "\\1", x), format = "%d.%m.%Y %H:%M")
    # [1] "2021-01-01 01:00:00 CET" "2021-01-01 02:00:00 CET" "2021-01-01 03:00:00 CET" "2021-01-01 04:00:00 CET"
    # [5] "2021-01-01 05:00:00 CET"
    

    sample data

    x <- c("01.01.2021 00:00 - 01.01.2021 01:00",
           "01.01.2021 01:00 - 01.01.2021 02:00",
           "01.01.2021 02:00 - 01.01.2021 03:00",
           "01.01.2021 03:00 - 01.01.2021 04:00",
           "01.01.2021 04:00 - 01.01.2021 05:00")