How to convert the number of hours into date format in r

Asked

Viewed 339 times

-2

I have a column in this format and I can’t convert it to date. At this time it is in hours. Example: 8.5 is actually 08:30:00 and so on... Any idea how to do it? (see image)

inserir a descrição da imagem aqui

start_date <- as.POSIXct(data$START, format = "%Y-%m-%d %H")
data <- mutate(data, START=start_date)

end_date <- as.POSIXct(data$END, format = "%Y-%m-%d %H")
data <- mutate(data, END=end_date)

When writing the code in this format what happens is that it "ignores" half hours, that is, for example, in the first line instead of Put 08:30:00 puts 08:00:00.

  • Post a sample of your data as text (for example, using dput - see the topic on minimum reproducible examples in the website help).

3 answers

2


The following function converts the dates with hours into numbers with decimals into dates with hours in the format HH:MM:SS.

dec2hour <- function(x){
  d <- sub("(^.*) .*$", "\\1", x)
  h <- sub("^.* ", "", x)
  h <- as.numeric(h)
  m <- h - floor(h)
  h <- floor(h)
  m <- m*60
  s <- m - floor(m)
  m <- floor(m)
  s <- s*60
  y <- paste(h, m, s, sep = ":")
  y <- as.POSIXct(paste(d, y))
  y
}

x <- c("2013-09-02 8.5", "2013-09-02 10", "2013-09-02 11.5", "2013-09-02 3.508333")
dec2hour(x)
#[1] "2013-09-02 08:30:00 WEST" "2013-09-02 10:00:00 WEST"
#[3] "2013-09-02 11:30:00 WEST" "2013-09-02 03:30:29 WEST"

Note: "WEST" is due to my time zone.

Sys.getlocale("LC_TIME")
#[1] "pt_PT.UTF-8"

2

If you only have full hours or half hours, you can use gsub to replace .5 for :30 before converting to POSIX. Write as a function to prevent code repetition when applying to the date.frame.

exemplo <- c('2013-09-02 8.5', '2013-09-02 9', '2013-09-02 10.5')

ajustaData <- function(x) {
  y <- paste0(x, ':00')
  y <- gsub('.5:00$', ':30', y)
  as.POSIXct(y, format = '%Y-%m-%d %H:%M')
}

> ajustaData(exemplo)
[1] "2013-09-02 08:30:00 -03" "2013-09-02 09:00:00 -03" "2013-09-02 10:30:00 -03"

1

To turn decimal hour into hour, just keep the amount of hour and multiply the minutes by 60.

Example: 1.50

I keep the 1 and take the minutes as 0.50 and then multiply by 60... so it becomes 30, now just concatenate 1|':'||30 and give a parse to date.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.