How to convert a date-T-time to just date?

Viewed 135

My date data comes with this type of format

a = structure(list(P_FPrescripcion = "2021-01-02T00:00:00"), row.names = c(NA, 
-1L), class = c("tbl_df", "tbl", "data.frame"))

im trying to maintain just the date portion of the data: 2021-01-02

i have used the as.date command multiple times before but im having trouble using it this time. This is the code i have so far:

as.Date(a, format="%Y-%m-%dT%H:%M:%S")
3 Answers

We need to extract the column as the object 'a' is a tibble

class(a)
[1] "tbl_df"     "tbl"        "data.frame"

Thus, extract the column with [[ using column index or column name (or with $)

as.Date(a[[1]], format="%Y-%m-%dT%H:%M:%S")
#[1] "2021-01-02"

Or use a short-form

as.Date(a[[1]], "%FT%T")
[1] "2021-01-02"

Or even without any format would also work

as.Date(a[[1]])
[1] "2021-01-02"

According to ?as.Date

The as.Date methods accept character strings, factors, logical NA and objects of classes "POSIXlt" and "POSIXct". (T


Or using dplyr

library(dplyr)
a %>%
     mutate(Date = as.Date(P_FPrescripcion))
# A tibble: 1 x 2
  P_FPrescripcion     Date      
  <chr>               <date>    
1 2021-01-02T00:00:00 2021-01-02

This also could be done through lubridate:

library(lubridate)

a %>% 
  mutate(P_FPrescripcion = as_date(ymd_hms(P_FPrescripcion)))

# A tibble: 1 x 1
  P_FPrescripcion
  <date>         
1 2021-01-02     

as.Date ignores junk at the end so this works:

as.Date(a[[1]])
## [1] "2021-01-02"
Related