I have a dataframe with date
column (its data type is factor) in format as follows:
uid date
<int> <fctr>
2970134 2019-12-31T17:05:00Z
2970204 2019-12-31T23:14:00Z
2970345 2020-01-01T11:00:00Z
I've converted them to the format 2019-12-31T00:00:00 0800
with code below:
data$date <- format(as.POSIXct(data$date), format='%Y-%m-%dT%H:%M:%S%z')
My question is I how to could I extract month from it? I tried with format(as.POSIXct(data$date_single, format='%Y-%m-%dT%H:%M:%S%z'),format='%m')
but it returns NA
s. Thanks.
CodePudding user response:
require(tidyverse)
require(lubridate) # Package for date and time manipulation
data %>%
mutate(month = month(date))
CodePudding user response:
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.