Search code examples
rdatetimeposixlt

Problem to convert string with month abbreviation to POSIXlt


I tried to convert Excel date character to date-time class using POSIXlt. This is an example of my data: "01:56:00 06-Apr-2017".

For the format, I used the character string giving a date-time format as used by strptime.

I tried as.POSIXlt(new_dtime, format = "%H:%M:%S %d-%b-%Y"), but it resulted in a bunch of NA. I am sure that the problem is related to the month abbreviation, despite I used %b as strptime suggests. Any help?


Solution

  • I'm going to take a guess that this is a locale problem: from ?strptime, %b denotes "[a]bbreviated month name in the current locale on this platform" (emphasis added). "Apr" is the abbreviation for April in an English locale. This question suggests the following solution:

    str1 <- "01:56:00 06-Apr-2017" 
    orig_locale <- Sys.getlocale("LC_TIME")
    Sys.setlocale("LC_TIME", "C")
    as.POSIXct(str1, format = "%H:%M:%S %d-%b-%Y")
    Sys.setlocale("LC_TIME", orig_locale)