Search code examples
rposixlt

Convert Date String in Format "Mon Day, Year Time am/pm" to POSIXlt format in R?


I'm trying to convert a string to a date time. I can't even get R to recognize and format the month though.

Here's a sample of the date formatting:

> for(i in sample_times){print(i)}
[1] "Aug 17, 2015 08:00 am"
[1] "Aug 15, 2015 12:06 am"
[1] "Jun 19, 2013 05:54 pm"
[1] "Aug 23, 2015 07:16 pm"
[1] "Aug 13, 2015 11:04 pm"
[1] "May 28, 2015 04:00 pm"
[1] "Jul 27, 2014 11:00 pm"
[1] "Aug 18, 2015 02:46 pm"
[1] "Aug 19, 2015 05:06 am"
[1] "Aug 25, 2015 07:27 pm"
[1] "Mar 12, 2014 10:14 am"
[1] "Aug 15, 2015 01:08 pm"
[1] "Aug 14, 2015 12:05 am"
[1] "Aug 18, 2015 11:07 am"
[1] "Aug 22, 2015 10:07 am"
[1] "Aug 24, 2015 12:38 pm"
[1] "Aug 21, 2015 08:17 pm"
[1] "Aug 23, 2015 08:34 pm"
[1] "Jun 11, 2015 09:44 pm"
[1] "Aug 23, 2015 01:54 pm"

Just calling strptime fails. Returns NAs.

Here's an example of what I tried, just to get the month out:

strptime(x = tolower(substr(sample_times, 0, 3)), format = "%b")

This returns NA for every value, even though tolower(substr(sample_times, 0, 3)) returns lower case month abbreviations

> tolower(substr(sample_times, 0, 3))
 [1] "aug" "aug" "jun" "aug" "aug" "may" "jul" "aug" "aug" "aug" "mar" "aug" "aug" "aug" "aug" "aug" "aug" "aug" "jun" "aug"

How do I convert my strings of dates to POSIXlt format? Sorry if this is a newb question: just getting started with time formatting in R.


Solution

  • You will want to use the format "%b %d, %Y %I:%M %p" in as.POSIXlt()

    • %b for the abbreviated month (in the current locale)
    • %d for the day
    • %Y for the full four-digit year
    • %I for the hour (when using %p a.k.a am/pm)
    • %M for the minutes
    • %p for am/pm

    So for a POSIXlt date-time, you can do

    (x <- as.POSIXlt("Aug 19, 2015 07:09 am", format = "%b %d, %Y %I:%M %p"))
    # [1] "2015-08-19 07:09:00 PDT"
    

    As mentioned in the comments, you must have created the entire POSIX object in order to extract its parts (well, to formally extract them anyway).

    months(x)
    # [1] "August"
    months(x, abbreviate = TRUE)
    # [1] "Aug"
    

    Additionally, in order to use strptime(), you must plan on creating the entire date-time object as you cannot just create a month and have it classed as such. See help(strptime) and help(as.POSIXlt) for more.