1
votes

In sample below the new_date column is in the expected format, the date column is in the chr format and the date is stored in it as a number. Is there a way to convert date time (char) to date time format without creating a new column?

df <- data.frame(id = c(1,2),
                 date = c("2013-09-15T00:00:00Z", "2014-09-13T00:00:00Z"), stringsAsFactors = F)

is.convertible.to.date <- function(x) !is.na(as.Date(as.character(x), tz = Sys.timezone(), format = '%Y-%m-%dT%H:%M:%SZ'))

str(df)

'data.frame': 2 obs. of 2 variables:
id : num 1 2
date: chr "2013-09-15T00:00:00Z" "2014-09-13T00:00:00Z"

DF_date <- sapply(df, is.convertible.to.date)
df$new_date <- as.Date(df[DF_date])
str(df)    

'data.frame': 2 obs. of 3 variables:
id : num 1 2
date : chr "2013-09-15T00:00:00Z" "2014-09-13T00:00:00Z"
new_date: Date, format: "2013-09-15" "2014-09-13"

DF_date <- sapply(df, is.convertible.to.date)
df[DF_date] <- as.Date(df[DF_date])

str(df)

'data.frame': 2 obs. of 3 variables:
id : num 1 2
date : chr "15963" "16326"
new_date: Date, format: "2013-09-15" "2014-09-13"

1
Please clarify what you're trying to achieve. You just want to overwrite an existing column? Easy: df$date <- as.Date(df$date, tz = Sys.timezone(), format = '%Y-%m-%dT%H:%M:%SZ')nevrome

1 Answers

0
votes

You can use the lubridate package.

library(lubridate)
df <- data.frame(id = c(1,2),
                 date = c("2013-09-15T01:00:00Z", "2014-09-13T00:00:00Z"), stringsAsFactors = F)

df$date <- ymd_hms(df$date)
str(df)
# 'data.frame': 2 obs. of  2 variables:
# $ id  : num  1 2
# $ date: POSIXct, format: "2013-09-15 01:00:00" "2014-09-13 00:00:00"

I made a small change from 2013-09-15T00:00:00Z to 2013-09-15T01:00:00Z, so you see it easily.