How to get month and year from complex date

My date column shows like this: "27 May 2016 10:08:13 AM"

All of my attempts result in a column filled with NA.

I have tried many things like:

df$Create_Month <- format(as.Date(df$`Create Date`, format="%d/%b/%Y %I:%M:%s %p"),"%Y-%m"))
df$Create_Month <- format(as.POSIXct(df$`Create Date`, format="%d/%b/%Y %I:%M:%s %p"),"%Y-%m"))
df[,"Create_Month"] <- format(as.Date(df$`Create Date`, format="%d/%b/%Y %I:%M:%s %p"),"%Y-%m"))
df[,"Create_Month"] <- format(df$`Create Date`,"%Y-%m"))

and variations on these, including dplyr piping, mutate, lubridate and etcetera.
Output in Terminal Is:

R> format(df$`Create Date`,"%Y %m"))
Error in format.default(Infocards$`Create Date`, "%Y %m") : 
invalid 'trim' argument

R> as.POSIXct("27 May 2016 10:08:13 AM", tz="EST", "%d %b %Y %i:%m:%s %p")
[1] NA

R> as.Date("27 May 2016 10:08:13 AM", "%d %b %Y %i:%m:%s %p")
[1] NA

Any help would be appreciated.

>Solution :

The %i, %m, %s should be upper case

as.POSIXct("27 May 2016 10:08:13 AM", tz="EST", "%d %b %Y %I:%M:%S %p")
[1] "2016-05-27 10:08:13 EST"

With this the format would work

format(as.POSIXct("27 May 2016 10:08:13 AM", tz="EST", 
  "%d %b %Y %I:%M:%S %p"), "%Y %m")
[1] "2016 05"

Leave a Reply