Home > OS >  There is date format from FRANCH, how to pase to normal format?
There is date format from FRANCH, how to pase to normal format?

Time:03-25

There is date format from FRANCH, how to pase to normal format? I want the format like 2022-2-7 2022 12:36:10 UTC

lubridate::dmy_hms("7 févr. 2022 12:35:10 UTC")

CodePudding user response:

There are two options (that I know of). If you have a French locale installed, you can set it as an option in your lubridate functions:

lubridate::dmy_hms("7 févr. 2022 12:35:10 UTC", locale = "fr_FR")

However, your French locale could be named differently (see this) and unless you installed your operating system in French, it is unlikely you have the locale installed in the first place.

The second option is to translate the month into your current locale. For me this is English, so I can whip up this quick function:

# get a dictionary first
months <- c(
  "janvier"   = "January",
  "février"   = "February",
  "mars"      = "March",
  "avril"     = "April",
  "mai"       = "May",
  "juin"      = "June",
  "juillet"   = "July",
  "août"      = "August",
  "septembre" = "September",
  "octobre"   = "October",
  "novembre"  = "November",
  "décembre"  = "December",
  # also include abbreviations
  "janv." = "January",
  "févr." = "February",
  "mars" = "March",
  "avril" = "April",
  "mai" = "May",
  "juin" = "June",
  "juil." = "July",
  "août" = "August",
  "sept." = "September",
  "oct." = "October",
  "nov." = "November",
  "déc." = "December"
)

# define a new function which includes translation
dmy_hms2 <- function(x) {
  x <- stringi::stri_replace_all_fixed(
    x,
    pattern = names(months),
    replacement = months,
    vectorize_all = FALSE
  )
  lubridate::dmy_hms(x)
}
# now it all works
dmy_hms2(x = "7 févr. 2022 12:35:10 UTC")
#> [1] "2022-02-07 12:35:10 UTC"

Created on 2022-03-25 by the reprex package (v2.0.1)

  • Related