Storing time without date but not as class character

自古美人都是妖i 提交于 2019-12-05 18:59:21

The chron package has a "times" class that might be helpful for you. Starting with something similar to what you have so far:

x <- c("1:30 AM", "6:29 AM", "6:59 AM", "9:54 AM", "10:14 AM", "3:15 PM"))
a <- as.POSIXct(x, tz = "", format = "%I:%M %p", usetz = FALSE)

Then we can use the times function with format

library(chron)
(tms <- times(format(a, "%H:%M:%S")))
# [1] 01:30:00 06:29:00 06:59:00 09:54:00 10:14:00 15:15:00
attributes(tms)
# $format
# [1] "h:m:s"
#
# $class
# [1] "times"

You can use the hms (hour-minute-second) series of functions in the lubridate package.

library(lubridate)

times = c("1:30 AM",  "6:29 AM",  "6:59 AM",  "9:54 AM", "2:45 PM")

I was hoping you could just do:

hm(times)
[1] "1H 30M 0S" "6H 29M 0S" "6H 59M 0S" "9H 54M 0S" "2H 45M 0S"

But notice that hm doesn't recognize the AM/PM distinction. So here's a more convoluted method that requires first using strptime, which does recognize AM/PM, and then putting the result in a form hm recognizes.

hm(paste0(hour(strptime(times, "%I:%M %p")),":",
          minute(strptime(times, "%I:%M %p"))))
[1] "1H 30M 0S"  "6H 29M 0S"  "6H 59M 0S"  "9H 54M 0S"  "14H 45M 0S"

There's probably a better way, but this seems to work.

UPDATE: To address your comment, you can use the hour and minute functions to get the hours and minutes (although I like @RichardScriven's answer better). For example:

hour(times)
[1]  1  6  6  9 14

mean(hour(times) + minute(times)/60)
[1] 7.923333
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!