Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading