I have a datetime column in a dataframe. Its in the POSIXct format. I want to set the seconds of all the rows (datetime column) to zero. Example, row 1 (datetime column), I want to convert 2022-05-09 20:00:22 to 2022-05-09 20:00:00. Similarly I want to set all seconds value to 00. Any help is appreciated. Here is some sample data:
dput(test_data)
structure(list(datetime = structure(c(1652140822, 1652140939,
1652141059, 1652141179, 1652141299, 1652141419, 1652141539, 1652141659,
1652141779, 1652141899, 1652142019, 1652142139, 1652142259, 1652142378,
1652142498, 1652142618, 1652142738, 1652142858, 1652142978, 1652143098
), tzone = "America/New_York", class = c("POSIXct", "POSIXt")),
pa_conc = c(5.57024, 5.57024, 5.57024, 5.57024, 5.57024,
5.57024, 5.57024, 5.57024, 5.57024, 5.57024, 5.57024, 5.57024,
5.57024, 5.57024, 5.57024, 5.57024, 5.57024, 5.57024, 5.57024,
5.57024)), row.names = c(NA, -20L), class = c("tbl_df", "tbl",
"data.frame"))
An option with lubridate
-
library(lubridate)
second(test_data$datetime) <- 0
test_data$datetime
# [1] "2022-05-09 20:00:00 EDT" "2022-05-09 20:02:00 EDT" "2022-05-09 20:04:00 EDT"
# [4] "2022-05-09 20:06:00 EDT" "2022-05-09 20:08:00 EDT" "2022-05-09 20:10:00 EDT"
# [7] "2022-05-09 20:12:00 EDT" "2022-05-09 20:14:00 EDT" "2022-05-09 20:16:00 EDT"
#[10] "2022-05-09 20:18:00 EDT" "2022-05-09 20:20:00 EDT" "2022-05-09 20:22:00 EDT"
#[13] "2022-05-09 20:24:00 EDT" "2022-05-09 20:26:00 EDT" "2022-05-09 20:28:00 EDT"
#[16] "2022-05-09 20:30:00 EDT" "2022-05-09 20:32:00 EDT" "2022-05-09 20:34:00 EDT"
#[19] "2022-05-09 20:36:00 EDT" "2022-05-09 20:38:00 EDT"