Search code examples
rtimestampstrptime

Parse timestamp with a.m./p.m


I have a file that formats time stamps like 25/03/2011 9:15:00 p.m.

How can I parse this text to a Date-Time class with either strptime or as.POSIXct?

Here is what almost works:

> as.POSIXct("25/03/2011 9:15:00", format="%d/%m/%Y %I:%M:%S", tz="UTC")
[1] "2011-03-25 09:15:00 UTC"

Here is what is not working, but I'd like to have working:

> as.POSIXct("25/03/2011 9:15:00 p.m.", format="%d/%m/%Y %I:%M:%S %p", tz="UTC")
[1] NA

I'm using R version 2.13.2 (2011-09-30) on MS Windows. My working locale is "C":

Sys.setlocale("LC_TIME", "C")

Solution

  • It appears the AM/PM indicator can't include punctuation. Try it after removing the punctuation:

    td <- "25/03/2011 9:15:00 p.m."
    tdClean <- gsub("(.)\\.?[Mm]\\.?","\\1m",td)
    as.POSIXct(tdClean, format="%d/%m/%Y %I:%M:%S %p", tz="UTC")
    # [1] "2011-03-25 21:15:00 UTC"