R将字符“111213”转换为适当的时间“11:12:13”
R convert character "111213" into proper time which is "11:12:13"
R 将字符“111213”转换为时间“11:12:13”。
strptime("111213", format="%H%m%s")
给出 NA
和
strptime("111213", "%H%m%s")
给出 1970-01-01 01:00:13 CET
我认为规范的答案应该是我的评论:
format(strptime("111213", format="%H%M%S"), "%H:%M:%S")
#[1] "11:12:13"
您可以在 ?strptime
中阅读所有详细信息。 format
是一个通用函数,在这个特定的例子中我们使用 format.POSIXlt
.
另一个解决方案是只使用字符串:
paste(substring("111213", c(1,3,5), c(2,4,6)), collapse = ":")
#[1] "11:12:13"
这是有道理的,因为您的输入确实不是 Date-Time:没有日期。
我们可以使用
library(chron)
times(gsub("(.{2})(?=\d)", "\1:", "111213", perl = TRUE))
#[1] 11:12:13
要操纵时间,您可以使用 hms
包。
默认情况下,它使用 %H:%M;%S
(或 %X
格式)。
对于您特定的时间格式 ("111213"
),您需要通过 base
函数 as.difftime
hms::as.hms(as.difftime("111213", format = "%H%M%S"))
#> 11:12:13
因此,如果我们也以类似的 "integer" 格式合并日期,我们可以获得命令:
strptime("20181017 112233", format="%Y%m%d %H%M%S")
R 将字符“111213”转换为时间“11:12:13”。
strptime("111213", format="%H%m%s")
给出 NA
和
strptime("111213", "%H%m%s")
给出 1970-01-01 01:00:13 CET
我认为规范的答案应该是我的评论:
format(strptime("111213", format="%H%M%S"), "%H:%M:%S")
#[1] "11:12:13"
您可以在 ?strptime
中阅读所有详细信息。 format
是一个通用函数,在这个特定的例子中我们使用 format.POSIXlt
.
另一个解决方案是只使用字符串:
paste(substring("111213", c(1,3,5), c(2,4,6)), collapse = ":")
#[1] "11:12:13"
这是有道理的,因为您的输入确实不是 Date-Time:没有日期。
我们可以使用
library(chron)
times(gsub("(.{2})(?=\d)", "\1:", "111213", perl = TRUE))
#[1] 11:12:13
要操纵时间,您可以使用 hms
包。
默认情况下,它使用 %H:%M;%S
(或 %X
格式)。
对于您特定的时间格式 ("111213"
),您需要通过 base
函数 as.difftime
hms::as.hms(as.difftime("111213", format = "%H%M%S"))
#> 11:12:13
因此,如果我们也以类似的 "integer" 格式合并日期,我们可以获得命令:
strptime("20181017 112233", format="%Y%m%d %H%M%S")