Home > Blockchain >  Convert "xx-xxx-xxxx" to date in R
Convert "xx-xxx-xxxx" to date in R

Time:10-01

I want to convert strings such as "19-SEP-2022" to date. Is there any available function in R? Thank you.

CodePudding user response:

Just to complete I want to add parse_date_time function from lubridate package. With no doubt, the preferred answer here is that of @Marco Sandri:

library(lubridate)

x <- "19-SEP-2022"

x <- parse_date_time(x, "dmy")
class(x)

[1] "2022-09-19 UTC"
> class(x)
[1] "POSIXct" "POSIXt" 

CodePudding user response:

Yes, strptime can be used to parse strings into dates.

You could do something like strptime("19-SEP-2022", "%d-%b-%Y").

If your days are not zero-padded, then use %e instead of %d.

CodePudding user response:

A decade or so ago I starting writing the anytime package because of the firm belief that for obvious date(time) patterns we should not need to specify patterns, or learn grammars.

I still use it daily, and so do a bunch of other CRAN users.

> anytime::anydate("19-SEP-2022")
[1] "2022-09-19"
>

So here we do exaxtly what you ask for: supply the string, return a date object.

  • Related