简体   繁体   中英

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:

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 = 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:

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:

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(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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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