Home > OS >  changing date/time variable to time that starts at 00:00:00 in r
changing date/time variable to time that starts at 00:00:00 in r

Time:03-30

I'm looking for a simple and correct way to change the date/time (POSIXct) format into a time that starts at 00:00:00.

I couldn't find an answer to this in R language, but if I overlooked one, please tell me :)

So I have this :

date/time v1
2022-02-16 15:07:15 38937
2022-02-16 15:07:17 39350

And I would like this :

time v1
00:00:00 38937
00:00:02 39350

Can somebody help me with this?

Thanks :)

CodePudding user response:

You can calculate the difference between the two datetimes in seconds, and add i to a random date starting at "00:00:00", before formatting it to only including the time. See the time column in the reprex underneath:

library(dplyr)
ibrary(lubridate)

df %>% 
  mutate(
    date = lubridate::ymd_hms(date),
    seconds = as.numeric(date - first(date)),
    time = format(
      lubridate::ymd_hms("2022-01-01 00:00:00")   seconds, 
      format = "%H:%M:%S"
    )
  )
#> # A tibble: 2 × 4
#>   date                   v1 seconds time    
#>   <dttm>              <dbl>   <dbl> <chr>   
#> 1 2022-02-16 15:07:15 38937       0 00:00:00
#> 2 2022-02-16 15:07:17 39350       2 00:00:02

Created on 2022-03-30 by the reprex package (v2.0.1)

Note that this will be misleading if you ever have over 24 hours between two datetimes. In these cases you should probably include the date.

Data

df <- tibble::tribble(
  ~date,    ~v1,
  "2022-02-16 15:07:15",    38937,
  "2022-02-16 15:07:17",    39350
)

CodePudding user response:

You can deduct all date/time with the first record of date/time, and change the result to type of time by the hms() function in the hms package.

library(dplyr)
library(hms)

df %>% 
  mutate(`date/time` = hms::hms(as.numeric(as.POSIXct(`date/time`) - as.POSIXct(first(`date/time`)))))

 date/time    v1
1  00:00:00 38937
2  00:00:02 39350

Note that in this method, even if the time difference is greater than 1 day, it'll be reflected in the result, for example:

df <- read.table(header = T, check.names = F, sep = "\t", text = "
date/time   v1
2022-02-16 15:07:15 38937
2022-02-18 15:07:17 39350")

df %>% 
  mutate(`date/time` = hms::hms(as.numeric(as.POSIXct(`date/time`) - as.POSIXct(first(`date/time`)))))

  date/time    v1
1  00:00:00 38937
2  48:00:02 39350
  • Related