2

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.

giraffehere
  • 1,118
  • 7
  • 18

3 Answers3

3

The most simplest solution would be

library(zoo)
as.Date(as.yearmon("Dec-18", "%b-%y"))
#[1] "2018-12-01"

The issue in the OP's code is that strptime or as.Date requires a day too. If it is not there, the format is not complete for a Date. One option would be to paste a day in strptime and it works

strptime(paste0("Dec-18", "-01"), format = "%b-%y-%d")
#[1] "2018-12-01 EST"
akrun
  • 874,273
  • 37
  • 540
  • 662
3

With lubridate, you can do:

parse_date_time("Dec-18", "my")

[1] "2018-12-01 UTC"
tmfmnk
  • 38,881
  • 4
  • 47
  • 67
2

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.

yarnabrina
  • 1,561
  • 1
  • 10
  • 30