简体   繁体   English

在 R 中将时间格式从 HH:MM:SS 更改为 HH:MM

[英]Change time format from HH:MM:SS to HH:MM in R

I'm tring to format a column with data type HH:MM:SS to HH:MM using this code:我正在尝试使用以下代码将数据类型为 HH:MM:SS 的列格式化为 HH:MM:

format(x, "%H:%M")

But i'm getting this:但我得到了这个:

 [1] "00:03:00" "00:13:00" "00:30:59" "00:52:00" "01:07:00" "00:48:00" "01:04:00" "01:10:59" "00:49:59" "01:00:59" "00:42:59"
[12] "00:48:00" "00:33:00" "00:36:00" "00:42:59" "00:26:00" "00:38:59" "00:45:00" "00:57:59" "01:08:59" "01:19:00" "01:28:00"
[23] "01:05:00"

My "x" is equal to:我的“x”等于:

x = c(0.05,
  0.2166667,
  0.5166667,
  0.8666667,
  1.116667,
  0.8,
  1.066667,
  1.183333,
  0.8333333,
  1.016667,
  0.7166666,
  0.8,
  0.55,
  0.6,
  0.7166666,
  0.4333333,
  0.65,
  0.75,
  0.9666666,
  1.15,
  1.316667,
  1.466667,
  1.083333)

x = hms::hms(lubridate::seconds_to_period(floor(unlist(x)* 60 *60)))

I don't know if format() works with objects from lubridate but for quick solution you could convert to character and remove the seconds:我不知道format()是否适用于来自lubridate的对象,但为了快速解决,您可以转换为字符并删除秒数:

sub(':[0-9]{2}$', '', as.character(x))
# [1] "00:03" "00:13" "00:31" "00:52" "01:07" ...

But given the numeric version of x you could also convert to POXISct which format() can deal with:但是给定x的数字版本,您也可以转换为 POXISct 哪个format()可以处理:

format(as.POSIXct(0, origin = '1970-01-01 00:00.00 UTC') + x*3600, '%H:%M')
# [1] "00:03" "00:13" "00:31" "00:52" "01:07" ...

You probably want the substr ings.您可能需要substr

substr(x, 1, 5)
# [1] "00:03" "00:13" "00:31" "00:52" "01:07" "00:48" "01:04" "01:10" "00:49" "01:01"
# [11] "00:42" "00:48" "00:33" "00:36" "00:42" "00:25" "00:39" "00:45" "00:57" "01:09"
# [21] "01:19" "01:28" "01:04"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM