Reputation: 41
I have an R dataset filled with character strings that look like this:
date <- "2019-03-12T14:32:24.000-01:00"
Is there a way to convert this date and time to a date class where both the date 2019-03-12 and the time T14:32:24.000-01:00 are displayed? I need a way to manipulate these dates later on, so I can find the time difference between two dates down to the seconds. I'm building the solution in R. Thanks!
Upvotes: 1
Views: 110
Reputation: 886938
We could use anytime
library(anytime)
anytime(date)
#[1] "2019-03-12 14:32:24 EDT"
If we want only the Date
, use anydate
anydate(date)
#[1] "2019-03-12"
In base R
, we can do
as.POSIXct(date, format = '%FT%T')
#[1] "2019-03-12 14:32:24 EDT"
date <- "2019-03-12T14:32:24.000-01:00"
Upvotes: 0
Reputation: 388817
You can use lubridate
's ymd_hms
.
date <- "2019-03-12T14:32:24.000-01:00"
date1 <- lubridate::ymd_hms(date)
date1
#[1] "2019-03-12 15:32:24 UTC"
Note that timezone has changed to UTC now and hence you see a different time.
If you only want the date you can use as.Date
and extract the time part with format
.
as.Date(date1)
#[1] "2019-03-12"
format(date1, '%T')
#[1] "15:32:24"
Upvotes: 2