rhjs
rhjs

Reputation: 231

R's as.POSIXct function gives NA, 30+ formats tested, time includes AM/PM

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

Answers (3)

jeremycg
jeremycg

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

milos.ai
milos.ai

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

Matt Parker
Matt Parker

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

Related Questions