Separating time and date into different columns (format=2019-05-26T13:50:56.335288Z)

138 views Asked by At

In my data, Time and date is stored in a column 'cord' (class=factor). I want to separate the date and the time into two separate columns.

The data looks like this:

1 2019-05-26T13:50:56.335288Z
2 2019-05-26T17:55:45.348073Z
3 2019-05-26T18:12:00.882572Z 
4 2019-05-26T18:26:49.577310Z 

I have successfully extracted the date using:cord$Date <- as.POSIXct(cord$Time)

I have however not been able to find a way to extract the time in format "H:M:S".

The output of dput(head(cord$Time)) returns a long list of timestamps: "2020-04-02T13:34:07.746777Z", "2020-04-02T13:41:11.095014Z", "2020-04-02T14:08:05.508818Z", "2020-04-02T14:17:10.337101Z", and so on...

2

There are 2 answers

0
Jonny Phelps On BEST ANSWER

I typically use lubridate and data.table to do my date and manipulation work. This works for me copying in some of your raw dates as strings

library(lubridate)
library(data.table)

x <- c("2019-05-26T13:50:56.335288Z", "2019-05-26T17:55:45.348073Z")
# lubridate to parse to date time
y <- parse_date_time(x, "ymd HMS")

# data.table to split in to dates and time
split_y <- tstrsplit(y, " ")
dt <- as.data.table(split_y)
setnames(dt, "Date", "Time")
dt[]

# if you use data.frames instead
df <- as.data.frame(dt)
df
1
Edo On

Extract H:M:S

library(lubridate)
format(as_datetime(cord$Time), "%H:%M:%S")
#> [1] "13:50:56" "17:55:45" "18:12:00" "18:26:49"

If you need milliseconds too:

format(as_datetime(cord$Time), "%H:%M:%OS6")
#> [1] "13:50:56.335288" "17:55:45.348073" "18:12:00.882572" "18:26:49.577310"

where cord is:

cord <- read.table(text = "  Time
1 2019-05-26T13:50:56.335288Z
2 2019-05-26T17:55:45.348073Z
3 2019-05-26T18:12:00.882572Z 
4 2019-05-26T18:26:49.577310Z ", header = TRUE)