Reputation: 231
I'm trying to convert the following date/time string to an POSIXct object:
19 Aug 2015 11:34 am
I tried 30+ approaches. Still getting NAs.
Here's the list of scripts that didn't work (just 4 examples):
as.POSIXct(toupper("19 Aug 2015 11:34 am"), format = "%d %b %Y %I:%M %p")
as.POSIXct(toupper("19 Aug 2015 11:34 am"), format = "%d %B %Y %I:%M %P")
as.POSIXct("19 Aug 2015 11:34 am", format = "%d %b %Y %I:%M %p")
as.POSIXct(toupper("19 Aug 2015 11:34 am"), tz = "UTC", format = '%d %b %Y %I:%M %p')
etc. Where's the mistake?
Upvotes: 1
Views: 284
Reputation: 24945
If you are in English, try:
as.POSIXct("19 Aug 2015 11:34 am", format = "%d %b %Y %I:%M %p")
If not, try:
Sys.setlocale("LC_ALL","English")
as.POSIXct("19 Aug 2015 11:34 am", format = "%d %b %Y %I:%M %p")
Explanation: strptime
is the formatting function used to change into POSIXct, and it uses the month names from your locale, as found in Sys.getlocale(category = "LC_TIME")
. If you give English names for months, you won't get a match if your locale is not English.
Upvotes: 3
Reputation: 3930
First set locale and then try conversion:
Sys.setlocale("LC_TIME", "C")
as.POSIXct("19 Aug 2015 11:34 am", format = "%d %b %Y %I:%M %p")
Upvotes: -1
Reputation: 27359
The problem with using toupper
is that it also uppercases your month, which doesn't fit the standard. But you can use regular expressions to target the am/pm bit more precisely:
yourtime <- c("19 Aug 2015 11:34 am", "19 Aug 2015 11:34 pm")
# Regular expressions to the rescue!
y <- sub(pattern = "(am|pm)", replacement = "\\U\\1", x = yourtime, perl = TRUE)
# Just AM and PM have been capitalized
y
# No problems, now
as.POSIXct(y, format = "%d %b %Y %I:%M %p")
Upvotes: 0