如何将时间从字符转换为时间并按小时分组

时间:2019-06-04 11:28:02

标签: r

需要将字符数据作为时间转换为实际时间并按小时分组

library(dplyr) 
library(stringr)
library(lubridate)
library(chron)
test <- read.csv("O:/Commercial Team/Customer Business Unit/ECOMMERCE and DIGITAL/9. TEAM/4_M_APPLEYARD.GEO.csv", header = TRUE)
colnames(test)
time <- str_split(test$ProcessedDate, " ", simplify = TRUE)
time2 <- c(time[,2])

3 个答案:

答案 0 :(得分:1)

签出strptime here。我不知道您的数据是什么样子,所以这是一个示例:

z <- strptime('2019-06-4 09:32:14', format = '%Y-%m-%d %H:%M%:S')

哪个给出输出[1] "2019-06-04 09:32:14 CEST"

您可以根据需要编辑格式。

编辑: 它以秒为单位,因此z + 3600 = "2019-06-04 10:32:14 CEST"

答案 1 :(得分:1)

您可以创建一个小时列并使用group_by()

library(tidyverse)
library(lubridate)

df <- tibble(ProcessedDate = sample(seq.POSIXt(from = as_datetime("2018-01-01 00:00:00"),
                                        to = as_datetime("2018-12-31 23:59:59"),
                                        by = "sec"), size = 1000, replace = TRUE),
             placeholder_value = rlnorm(n = 1000))

df2 <- df %>% 
  mutate(Processed_hour = hour(ProcessedDate),
         Processed_minute = minute(ProcessedDate),
         Processed_second = second(ProcessedDate)) %>% 
  group_by(Processed_hour) %>%
  summarise(sum = sum(placeholder_value)) 

print(df2, n = Inf)

ggplot(df2, aes(x = as_factor(Processed_hour), y = sum)) +
  geom_col()

答案 2 :(得分:0)

基本上是larsoevlisen答案的一个简单版本,因为我认为您可以使用lubridate来做所有事情(但是如果没有数据样本就很难说):

library(tidyverse)
library(lubridate)

#create imaginary data set for this answer
#skip this step if you already have your data
df <- tibble(yourtimestamp = c("2019-06-04 11:20", "2019-06-04 11:25", "2019-06-04 12:00"))

#convert your timestamp vector to POSIX
df$yourtimestamp <- ymd_hm(df$yourtimestamp)
#the function you use here depends on what order the parts of your time stamp are, 
#so for example if your character timestamp is US style: month, day, year 
#such as 
#06/20/2019 11:20 then use mdy_hm() instead
#or if it was UK style 20/06/2019 11:20 then use dmy_hm() etc
#or if it contains seconds such as 06/20/2019 11:20:47 use mdy_hms()

#get hour
df$just_the_hour <- hour(df$yourtimestamp)

#group by hour and summarise
by_hour <- group_by(df, just_the_hour)
s <- summarise(by_hour, num_events = n())
s

输出:

# A tibble: 2 x 2
  just_the_hour num_events
          <int>      <int>
1            11          2
2            12          1