1
In a table column, I have the values of DATE and TIME in the same field.
Example:
23:02:1989 14:22
I need to separate the Date and Time Value.
How should I do?
Thank you,
1
In a table column, I have the values of DATE and TIME in the same field.
Example:
23:02:1989 14:22
I need to separate the Date and Time Value.
How should I do?
Thank you,
4
You can use the function strptime()
and others more that I put in the example:
x <- "23:02:1989 14:22"
dataHora <-strptime(x, "%d:%m:%Y %H:%M") # converte para o formato adequado
# [1] "1989-02-23 14:22:00 GMT"
And if you want to separate in date and time:
data <- as.Date(dataHora, "%d:%m:%Y")
hora <- format(dataHora, "%H:%M")
2
Another alternative is to use the package lubridate
, that is part of the tidyverse.
Then we would have:
library(lubridate)
x <- "23:02:1989 14:22"
data_hora <- dmy_hm(x)
class(data_hora)
[1] "POSIXct" "POSIXt"
The function dmy_hm()
parses dates that are in day, month, year, time and minute format.
The solution offered by @Willianvieira leaves the hours in a text format. In this case it can also be done with text manipulation. In tidyverse, this is done with the package stringr.
library(stringr)
separados <- str_split(x, " ")[[1]]
separados[1]
[1] "23:02:1989"
separados[2]
[1] "14:22"
After the separation of the texts it is possible to parse the date and time separately.
dt_data <- dmy(separados[1])
class(dt_data)
[1] "Date"
hm_data <- hm(separados[2])
class(hm_data)
[1] "Period"
attr(,"package")
[1] "lubridate"
Another widely used alternative with the lubridate
, which has a tone of gambiarra, is to make all the elements of a date and time vector have the same day. So the differences in the hour are thrown to the foreground.
hora <- data_hora + duration(5:14, "hours")
year(hora) <- 1989
month(hora) <- 1
day(hora) <- 1
hora
[1] "1989-01-01 19:22:00 UTC" "1989-01-01 20:22:00 UTC"
[3] "1989-01-01 21:22:00 UTC" "1989-01-01 22:22:00 UTC"
[5] "1989-01-01 23:22:00 UTC" "1989-01-01 00:22:00 UTC"
[7] "1989-01-01 01:22:00 UTC" "1989-01-01 02:22:00 UTC"
[9] "1989-01-01 03:22:00 UTC" "1989-01-01 04:22:00 UTC"
Browser other questions tagged r
You are not signed in. Login or sign up in order to post.