将秒数转换为HH:MM

时间:2017-03-20 12:16:34

标签: r

由于导入缺陷,我有一个秒数而不是时间的列。

我设法通过使用lubridate包将秒转换为xxH xxM xxS格式。

dt$column <- seconds_to_period(dt$column)

但我需要的是14:30而不是14H 30M 00S。我尝试了以下但现在我的时间栏中只有NA:

myTime <- "14:11:49"
hms(myTime)
POSIXct_myTime <- parse_date_time(myTime,"hms")
format(POSIXct_myTime, format="%H:%M")
Dataset$Aanvangstijdstip <- format(POSIXct_myTime, format="%H:%M")

head(df$column) gives: [1] "17H 0M 0S"  "20H 0M 0S"  "9H 0M 0S"   "14H 30M 0S" "10H 15M 0S" "14H 30M 0S"

1 个答案:

答案 0 :(得分:0)

您可以尝试按照所有这些行来将秒字段转换为HH:MM格式的字符串:

library(data.table)
library(lubridate)

# create sample data
dt <- data.table(seconds_of_day = 60 * 15 * seq(11, 77, 11))
# convert seconds to period
dt[, period := seconds_to_period(seconds_of_day)]
# convert period to time of day _as character string_ !
dt[, time_of_day := sprintf("%02i:%02i", hour(period), minute(period))]
dt
#   seconds_of_day     period time_of_day
#1:           9900  2H 45M 0S       02:45
#2:          19800  5H 30M 0S       05:30
#3:          29700  8H 15M 0S       08:15
#4:          39600  11H 0M 0S       11:00
#5:          49500 13H 45M 0S       13:45
#6:          59400 16H 30M 0S       16:30
#7:          69300 19H 15M 0S       19:15

或者,将seconds_of_day转换为period个对象的中间步骤可以通过转换为类POSIXct来替换。但是,我们确实需要一个参考日期,其中可以添加秒数:

ref_date <- ymd("2017-01-01", tz = "UTC")
dt[, time_of_day2 := format(ref_date + seconds_of_day, "%H:%M")]
dt
#   seconds_of_day     period time_of_day time_of_day2
#1:           9900  2H 45M 0S       02:45        02:45
#2:          19800  5H 30M 0S       05:30        05:30
#3:          29700  8H 15M 0S       08:15        08:15
#4:          39600  11H 0M 0S       11:00        11:00
#5:          49500 13H 45M 0S       13:45        13:45
#6:          59400 16H 30M 0S       16:30        16:30
#7:          69300 19H 15M 0S       19:15        19:15

请注意,参数tz = "UTC"ymd()对于确保解决方案独立于本地时区至关重要。