Hour/minute 使用 lubridate 从日期时间增加一小时

Hour/minute adds one hour from datetime with lubridate

我想从日期时间中提取 hour/minute/second。示例数据框:

df <- structure(list(Study_date_time_PACS = structure(c(1515146548, 1515146548, 1514970658, 1514970658, 1515151732, 1515151732, 1517476589, 1517476589, 1543848246, 1543848246),
                                                class = c("POSIXct", "POSIXt"), 
                                                tzone = "UTC")),
          .Names = "Study_date_time", 
          row.names = c(NA, -10L), 
          class = c("tbl_df", "tbl", "data.frame"))
print(df)


# A tibble: 10 x 1
   Study_date_time    
   <dttm>             
 1 2018-01-05 10:02:28
 2 2018-01-05 10:02:28
 3 2018-01-03 09:10:58
 4 2018-01-03 09:10:58
 5 2018-01-05 11:28:52
 6 2018-01-05 11:28:52
 7 2018-02-01 09:16:29
 8 2018-02-01 09:16:29
 9 2018-12-03 14:44:06
10 2018-12-03 14:44:06

所以我 运行 这个代码但是它会在 "hour" 上增加一小时?我怎样才能解决这个问题。我想这一定是夏天的事...

library(lubridate)
df %>% 
  mutate(hour_min = hms::as.hms(Study_date_time))

# A tibble: 10 x 2
   Study_date_time     hour_min
   <dttm>              <time>  
 1 2018-01-05 10:02:28 11:02   
 2 2018-01-05 10:02:28 11:02   
 3 2018-01-03 09:10:58 10:10   
 4 2018-01-03 09:10:58 10:10   
 5 2018-01-05 11:28:52 12:28   
 6 2018-01-05 11:28:52 12:28   
 7 2018-02-01 09:16:29 10:16   
 8 2018-02-01 09:16:29 10:16   
 9 2018-12-03 14:44:06 15:44   
10 2018-12-03 14:44:06 15:44  

可能是由于时区元素被剥夺了...让我猜猜:你住在地球上的 UTC+0100 区域?

您可以使用 lubridate-package 中的 force_tz() 函数..但要小心!!时区总是很麻烦,所以要小心处理!

df %>% mutate(hour_min = hms::as.hms( force_tz( Study_date_time ) ) )

# # A tibble: 10 x 2
#   Study_date_time     hour_min
#   <dttm>              <time>  
# 1 2018-01-05 10:02:28 10:02   
# 2 2018-01-05 10:02:28 10:02   
# 3 2018-01-03 09:10:58 09:10   
# 4 2018-01-03 09:10:58 09:10   
# 5 2018-01-05 11:28:52 11:28   
# 6 2018-01-05 11:28:52 11:28   
# 7 2018-02-01 09:16:29 09:16   
# 8 2018-02-01 09:16:29 09:16   
# 9 2018-12-03 14:44:06 14:44   
# 10 2018-12-03 14:44:06 14:44 

我同意这可能是一个 tz 问题(也许你可以 hms::as.hms(Study_date_time, tz = 'UTC')) 然后它就会消失),但是我认为你在没有任何包裹的情况下也能做得很好,例如:

df %>% 
  mutate(hour_min = format(Study_date_time, "%H:%M"))