【发布时间】:2022-02-04 12:23:15
【问题描述】:
我在数据框中有一列是午夜过后的秒数。我将如何将该数字转换为显示为 hh:mm:ss 的时间?例如:
| hrsecs |
|---|
| 1563 |
| 13088 |
| 14309 |
变成
| Time |
|---|
| 00:26:03 |
| 03:38:08 |
| 03:58:29 |
【问题讨论】:
我在数据框中有一列是午夜过后的秒数。我将如何将该数字转换为显示为 hh:mm:ss 的时间?例如:
| hrsecs |
|---|
| 1563 |
| 13088 |
| 14309 |
变成
| Time |
|---|
| 00:26:03 |
| 03:38:08 |
| 03:58:29 |
【问题讨论】:
将秒数转换为句点 (seconds_to_period) 并使用 hms 包中的 hms
library(lubridate)
library(dplyr)
df1 <- df1 %>%
transmute(Time = hms::hms(seconds_to_period(hrsecs)))
-输出
df1
Time
1 00:26:03
2 03:38:08
3 03:58:29
df1 <- structure(list(hrsecs = c(1563L, 13088L, 14309L)),
class = "data.frame", row.names = c(NA,
-3L))
【讨论】:
1) 字符输出 转换成POSIXct再格式化。没有使用任何包。
x <- c(1563, 13088, 14309)
tt <- format(as.POSIXct("1970-01-01") + x, "%T"); tt
## [1] "00:26:03" "03:38:08" "03:58:29"
或
tt <- format(structure(x, class = c("POSIXct", "POSIXt"), tzone = "UTC"), "%T")
tt
## [1] "00:26:03" "03:38:08" "03:58:29"
2) 时间类输出如果您希望能够操纵时间,那么这将在内部将它们表示为一天的分数,但将它们呈现为时间。
library(chron)
times(tt)
## [1] 00:26:03 03:38:08 03:58:29
【讨论】: