Search code examples
rregex

Time conversion in R


In R, I have a data frame with a column called “time” with entries such as “1 hour ago”, “2 hours ago”, and “38 minutes ago”. How do I convert these to a standard date/time format based on the system time, like “2025-03-09 01:30:00”?


Solution

  • Here is a base R solution.

    Note: This handles cases where the string contains "hour" OR "minute" like in your examples. This code get's numeric values from the string and assumes the unit (h/m) by matching string patterns. Depending on the unit and num the time is subtracted from the current sys.time(). You might want to handle more cases in the if statement depending on more unnamed units (seconds / days / weeks)

    df <- data.frame(time = c("1 hour ago", "2 hours ago", "38 minutes ago"))
    df$num <- as.numeric(gsub("([0-9]+).*", "\\1", df$time))
    df$unit <- gsub(".*([0-9]+) ([a-z]+).*", "\\2", df$time) # get Word after numeric
    df$unit <- gsub("s$", "", df$unit)  # remove s if it exists
    df$timestamp <- Sys.time() - ifelse(df$unit == "hour", df$num * 3600, df$num * 60)
    df
    
                time num   unit           timestamp
    1     1 hour ago   1   hour 2025-03-09 22:12:56
    2    2 hours ago   2   hour 2025-03-09 21:12:56
    3 38 minutes ago  38 minute 2025-03-09 22:34:56