How to Extract Month from Date in R

How to extract Month from date in R

?month states:

Date-time must be a POSIXct, POSIXlt, Date, Period, chron, yearmon,
yearqtr, zoo, zooreg, timeDate, xts, its, ti, jul, timeSeries, and fts
objects.

Your object is a factor, not even a character vector (presumably because of stringsAsFactors = TRUE). You have to convert your vector to some datetime class, for instance to POSIXlt:

library(lubridate)
some_date <- c("01/02/1979", "03/04/1980")
month(as.POSIXlt(some_date, format="%d/%m/%Y"))
[1] 2 4

There's also a convenience function dmy, that can do the same (tip proposed by @Henrik):

month(dmy(some_date))
[1] 2 4

Going even further, @IShouldBuyABoat gives another hint that dd/mm/yyyy character formats are accepted without any explicit casting:

month(some_date)
[1] 2 4

For a list of formats, see ?strptime. You'll find that "standard unambiguous format" stands for

The default formats follow the rules of the ISO 8601 international
standard which expresses a day as "2001-02-28" and a time as
"14:01:02" using leading zeroes as here.

Extract month and year from datetime in R

lubridate month and year will work.

as.data.frame(Order.Date) %>%
mutate(Month = lubridate::month(Order.Date, label = FALSE),
Year = lubridate::year(Order.Date))

Order.Date Month Year
1 2011-10-20 10 2011
2 2011-12-25 12 2011
3 2012-04-15 4 2012
4 2012-08-23 8 2012
5 2013-09-25 9 2013

If you want month format as Jan, use month.abb and as January, use month.name

as.data.frame(Order.Date) %>%
mutate(Month = month.abb[lubridate::month(Order.Date, label = TRUE)],
Year = lubridate::year(Order.Date))

Order.Date Month Year
1 2011-10-20 Oct 2011
2 2011-12-25 Dec 2011
3 2012-04-15 Apr 2012
4 2012-08-23 Aug 2012
5 2013-09-25 Sep 2013

as.data.frame(Order.Date) %>%
mutate(Month = month.name[lubridate::month(Order.Date, label = TRUE)],
Year = lubridate::year(Order.Date))

Order.Date Month Year
1 2011-10-20 October 2011
2 2011-12-25 December 2011
3 2012-04-15 April 2012
4 2012-08-23 August 2012
5 2013-09-25 September 2013

Extract Month and Year From Date in R

This will add a new column to your data.frame with the specified format.

df$Month_Yr <- format(as.Date(df$Date), "%Y-%m")

df
#> ID Date Month_Yr
#> 1 1 2004-02-06 2004-02
#> 2 2 2006-03-14 2006-03
#> 3 3 2007-07-16 2007-07

# your data sample
df <- data.frame( ID=1:3,Date = c("2004-02-06" , "2006-03-14" , "2007-07-16") )

a simple example:

dates <- "2004-02-06"

format(as.Date(dates), "%Y-%m")
> "2004-02"

side note:
the data.table approach can be quite faster in case you're working with a big dataset.

library(data.table)
setDT(df)[, Month_Yr := format(as.Date(Date), "%Y-%m") ]

How to extract Month and Year from Date column and add two more columns for each

Looks like it is grabbing the day instead of the year. So would seem that your date isn't properly formatted when it goes through the as.Date() function

See what this

as.Date(act_weather_data$Date)

looks like on its own and format accordingly

i.e.

as.Date(act_weather_data$Date, format="%Y/%m/%d")

Then apply.the formatting as before
i.e

Year=format(as.Date(act_weather_data$Date, format="%Y/%m/%d"),"%Y")

extract month date year into new columns from char column in R

You can use tidyr::separate

library(tidyverse)
data <- data.frame(date = "2021-18-02 16:08:48")

data %>%
separate(date, into = c("Year","Day","Month","Time"), extra = "merge")

# Year Day Month Time
# 1 2021 18 02 16:08:48

Extract month from date with dplyr

With case_when, the 'type' should be the same across the output from all the conditions. In the first case, we convert to 'Date' from the numeric column across the 'col' columns, then reconvert it to character class to avoid a clash with other values. In the 'col1_month', the 'col1' is converted to Date again before extracting the month

library(dplyr)
library(lubridate)
df %>%
mutate(across(starts_with('col'),
~ case_when(nchar(.) > 4 ~
as.character(as.Date(., origin = '1899-12-30')),
TRUE ~ as.character(.))),
col1_month = case_when(nchar(col1) == 10 ~
as.character(month(as.Date(col1))), TRUE ~ col1))

-output

#        col1       col2 col1_month
#1 2020-06-26 2019-01-11 6
#2 2020-06-19 2019-01-14 6
#3 <NA> 77 <NA>
#4 77 <NA> 77

How to extract month from a column in R

We can use couple of ways to do this. Regex option would be to remove the characters until the - with sub on the 'date' column

FF5_class$Month <- sub(".*-", "", FF5_class$date))

Or convert to a Date class after pasteing the day, then use format

FF5_class$Month <- format(as.Date(paste0(FF5_class$date, '-01')), '%m')

month works only a Date object and not on a character class

Extract month from ISO-8601 format date using R

You have a small logic error. You take your input data and parse it -- so far, so good:

> v <- c("2019-12-31T17:05:00Z", "2019-12-31T23:14:00Z", "2020-01-01T11:00:00Z")
> pt <- as.POSIXct(v)
> pt
[1] "2019-12-31 CST" "2019-12-31 CST" "2020-01-01 CST"
>

Now that you have date(time) information, you can format() or strftime() as you like:

> strftime(pt, "%m")
[1] "12" "12" "01"
> strftime(pt, "%b")
[1] "Dec" "Dec" "Jan"
> strftime(pt, "%B")
[1] "December" "December" "January"
>

Converting from character to int is also easy. Note that all this was done with base R without any additional packages.

How to extract 'month' from date given in character form?

You can convert the string as a datatime object by calling the function as.POSXct(). Then you can use the format() function to just show the month from 1 to 12. Below is an example:

> datestring <- c('01-Dec-2016', '01-Jan-2017','01-Feb-2017')
> datetime <- as.POSIXct(datestring, format = '%d-%b-%Y')
> datetime
[1] "2016-12-01 CST" "2017-01-01 CST" "2017-02-01 CST"
> as.numeric(format(datetime, '%m'))
[1] 12 1 2


Related Topics



Leave a reply



Submit