Convert date-time string to class Date
You may be overcomplicating things, is there any reason you need the stringr package? You can use as.Date
and its format
argument to specify the input format of your string.
df <- data.frame(Date = c("10/9/2009 0:00:00", "10/15/2009 0:00:00"))
as.Date(df$Date, format = "%m/%d/%Y %H:%M:%S")
# [1] "2009-10-09" "2009-10-15"
Note the Details section of ?as.Date
:
Character strings are processed as far as necessary for the format specified: any trailing characters are ignored
Thus, this also works:
as.Date(df$Date, format = "%m/%d/%Y")
# [1] "2009-10-09" "2009-10-15"
All the conversion specifications that can be used to specify the input format
are found in the Details section in ?strptime
. Make sure that the order of the conversion specification as well as any separators correspond exactly with the format of your input string.
More generally and if you need the time component as well, use as.POSIXct
or strptime
:
as.POSIXct(df$Date, "%m/%d/%Y %H:%M:%S")
strptime(df$Date, "%m/%d/%Y %H:%M:%S")
I'm guessing at what your actual data might look at from the partial results you give.
How to convert character to date with two different types of date formats in R?
You can do something like:
format_ymd <- as.Date(dates, format = "%Y-%m-%d")
format_dmy <- as.Date(dates, format = "%d/%m/%Y")
as.Date(ifelse(is.na(format_ymd), format_dmy, format_ymd), origin = "1970-01-01")
# [1] "2022-04-08" "2021-01-26" "2021-07-14" "2021-12-27"
Convert an entire column from character to date class in R
Replacing the '.' with '/' works from your first example in the format:
Date <- mutate(crime, ArrestDate = as.Date(ArrestDate, format= "%m/%d/%Y"))
class(Date$ArrestDate)
[1] "Date"
Convert Character to date
how about just overwriting that column as a date column:
library(tidyverse)
data <- data %>% mutate(InvoiceDate = dmy_hm(InvoiceDate)) #dmy_hm() converts to date
#or if you really need a separate vector:
data1 <- dmy_hm(data$InvoiceDate)
you can read about dmy_hm()
and similar functions in the tidyverse's sublibrary lubridate
. I find it very useful.
How to convert to character to date in R?
If you have locale same as the data that you have using lubridate
's mdy_hms
should work.
df$date <- lubridate::mdy_hms(df$date)
How to convert character to Date format in R?
Since you have only year
and month
, you need to assign some value for day
before you convert to date. In the example below, the day has arbitrarily been chosen as 15
.
IF THE INPUT IS CHARACTER
dates = c("2012.10", "2012.01")
lubridate::ymd(paste0(year_month = dates, day = "15"))
#[1] "2012-10-15" "2012-01-15"
IF THE INPUT IS NUMERIC
dates = c(2012.10, 2012.01)
do.call(c, lapply(strsplit(as.character(dates), "\\."), function(d){
if(nchar(d[2]) == 1){
d[2] = paste0(d[2],"0")
}
lubridate::ymd(paste0(year = d[1], month = d[2], day = "15"))
}))
#[1] "2012-10-15" "2012-01-15"
How to convert character into date format in R
A base R option (assuming that there are only two formats in the OP's 'create_date' column), will be to create a logical index with grepl
for those date elements that start with 'year', subset the 'create_date' based on the logical index ('i1'), convert to Date
class separately and assign those separately to a Date
vector of the same length as the number of rows of the dataset to create the full Date
class.
i1 <- grepl("^[0-9]{4}", df$create_date)
v1 <- as.Date(df$create_date[i1])
v2 <- as.Date(df$create_date[!i1], "%m/%d/%Y")
v3 <- Sys.Date() + 0:(nrow(df)-1)
v3[i1] <- v1
v3[!i1] <- v2
df$create_date <- v3
Or as I commented in the OP's post (first) parse_date_time
from lubridate
can be used
library(lubridate)
as.Date(parse_date_time(df$create_date, c('mdy', 'ymd_hms')))
#[1] "2016-08-13" "2016-08-13" "2016-08-13" "2016-08-13"
#[5] "2016-08-13" "2016-08-13" "2016-08-13"
data
df <- structure(list(create_date = c("8/13/2016", "8/13/2016",
"8/13/2016",
"2016-08-13T08:26:04Z", "2016-08-13T14:30:23Z", "8/13/2016",
"8/13/2016")), .Names = "create_date", class = "data.frame",
row.names = c(NA, -7L))
Related Topics
Difference Between Mean(C(1,2,21)) and Mean(1,2,21)
Extract Nested List Elements Using Bracketed Numbers and Names
What Is the Knitr Equivalent of 'R Cmd Sweave Myfile.Rnw'
More Efficient Means of Creating a Corpus and Dtm with 4M Rows
Make Dataframe of Top N Frequent Terms for Multiple Corpora Using Tm Package in R
Use Dplyr's Summarise_Each to Return One Row Per Function
Use of Switch() in R to Replace Vector Values
How to Stop Emacs from Replacing Underbar with <- in Ess-Mode
Convert Data Frame into Vector
Which Library Could Be Used to Make a Chord Diagram in R
How to Identify the Distribution of the Given Data Using R
Street Address to Geolocation Lat/Long
Specifying Column Types When Importing Xlsx Data to R with Package Readxl