分析日期时间变量的日期时间

时间:2016-05-13 06:54:42

标签: r lubridate

这就是我解决问题的方法:

datestimes <- c("2014-01-01 23:03:00", "2014-01-02 00:35:00", "2014-01-02 00:51:00") # There is a change in date. 
# Is there any lubridate command for the following step?    
time <- as.POSIXct(strftime(datetimes, format = "%H:%M:%S", tz = "UTC"), format = "%H:%M:%S") 
time  
[1] "2016-05-13 23:03:00 CEST" "2016-05-13 00:35:00 CEST" "2016-05-13 00:51:00 CEST"

有没有理由在lubridate中没有这样的功能? 正如我所说 - 我只对时间部分感兴趣 - 而不是日期。

lubridate::hms给出了句号:

ltime <- lubridate::hms(strftime(datetimes, format = "%H:%M:%S", tz = "UTC"))  
ltime  
[1] "23H 3M 0S" "35M 0S"    "51M 0S"  
class(ltime)  
[1] "Period"  
attr(,"package")  
[1] "lubridate"

2 个答案:

答案 0 :(得分:1)

这个怎么样?

library(lubridate)
datetimes <- c("2014-01-01 23:03:00", "2014-01-02 00:35:00", "2014-01-02 00:51:00") 
dataset <- data.frame(
  time = as.POSIXct(strftime(datetimes, format = "%H:%M:%S", tz = "UTC"), format = "%H:%M:%S") 
)
dataset$delta <- dataset$time - floor_date(dataset$time, unit = "day")
dataset$relative <- as.POSIXct("2001-01-01 0:0:0") + minutes(dataset$delta)

library(ggplot2)
ggplot(dataset, aes(x = relative)) + 
  geom_histogram(binwidth = 3600) + 
  scale_x_datetime(date_breaks = "3 hour", date_labels = "%H:%M")

答案 1 :(得分:1)

感谢alistair:ymd_hms(paste(today(), format(ymd_hms(datetimes), '%T')))将是我的选择。这可以很好地与histggplot2结合使用(见上文)。