Search code examples
rdate-formatstrptime

R strptime issue when using %b to format a date


Before marking as duplicate, I've tried a few other solutions, namely these:

R, strptime(), %b, trying to convert character to date format

strptime, as.POSIXct and as.Date return unexpected NA

But neither seem to work for me.


I'm trying to convert a time format Dec-18 to a POSIXct time (would be 2018-12-01 in this case). I'm attempting to use strptime with %b and %y to achieve this as so:

> strptime("Dec-18", format = "%b-%y")
[1] NA

But obviously it is not working. I'm reading a out about "locales" and such, but the above solutions did not work for me. I attempted the following:

> Sys.setlocale("LC_TIME", "C")
[1] "C"
> strptime("Dec-18", format = "%b-%y")
[1] NA

It was also suggested to use this locale, Sys.setlocale("LC_TIME", "en_GB.UTF-8"), but I get an error when trying to use this:

> Sys.setlocale("LC_TIME", "en_GB.UTF-8")
[1] ""
Warning message:
In Sys.setlocale("LC_TIME", "en_GB.UTF-8") :
  OS reports request to set locale to "en_GB.UTF-8" cannot be honored

Kind of at a loss for what to do here. My abbreviated months seem right based off this:

> month.abb
 [1] "Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "Dec"

Here's the version of R that I am running:

R version 3.5.3 (2019-03-11) -- "Great Truth"
Copyright (C) 2019 The R Foundation for Statistical Computing
Platform: x86_64-w64-mingw32/x64 (64-bit)

Thanks in advance.


Solution

  • The simplest solution will be this:

    as.Date(x = paste0("01-", "Dec-18"),
            format = "%d-%b-%y")
    #> [1] "2018-12-01"
    
    format(x = as.Date(x = paste0("01-", "Dec-18"),
                       format = "%d-%b-%y"),
           format = "%b-%y")
    #> [1] "Dec-18"
    

    Created on 2019-05-15 by the reprex package (v0.2.1)

    R doesn't recognise Dec-18 as date. Add a 01- so that it can detect it as date, and then display as you prefer.