Home > Mobile >  How to get month and year from complex date
How to get month and year from complex date

Time:12-28

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.

CodePudding user response:

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"

CodePudding user response:

Try parse_date() function from parse_date package:

library(parsedate)
parse_date(x)

[1] "2016-05-27 10:08:13 UTC"

CodePudding user response:

import datetime currentDate=datetime.date.today() currentMonthName=currentDate.strftime("%B") print(currentDate) print(currentMonthName)

The strftime() function is used to convert date and time objects to their string representation. It takes one or more input of formatted code and returns the string representation.

%B represent the Full month name like January, February and so on.

  • Related