在R中将数值变量转换为时间变量

时间:2019-08-09 06:40:32

标签: r time character numeric

我的加载时间为hh:mm 1。但是,当我使用read excel(readxl)读取数据时,它显示为数字2。因此,我想将这些值转换为hh:mm agian中的时间,或者有什么方法可以读取此文件而不转换为数字。

as.POSIXlt(0.2743) as.POSIXlt.numeric(0.2743)中的错误:必须提供'origin'

1 个答案:

答案 0 :(得分:0)

您可以使用hms::hms

library(hms)

hms(days = 0.2743)
#> 06:34:59.52

hms(days = 0.31597)
#> 07:34:59.808

hms(days = 1)
#> 24:00:00

POSIXlt的对象也包含日期部分,如果提供了数字输入,我们需要指定从哪个起点开始计算秒数,例如:

## 1 minute from 1970-01-01 00:00:00 UTC
as.POSIXlt(60, origin = "1970-01-01", tz = "UTC")
#> [1] "1970-01-01 00:01:00 UTC"

或者,如果输出的格式应为hh:mm,而不是hh:mm:ss函数,如hms函数,我们可以将formatas.POSIXlt一起使用,并虚拟起点:

format(as.POSIXlt(0.2743 * 3600 * 24, origin = Sys.Date(), tz = "UTC"), "%H:%M")
#> [1] "06:34"

format(as.POSIXlt(0.31597 * 3600 * 24, origin = Sys.Date(), tz = "UTC"), "%H:%M")
#> [1] "07:34"
相关问题