【问题标题】:Hour/minute adds one hour from datetime with lubridate小时/分钟使用 lubridate 从日期时间增加一小时
【发布时间】:2019-02-15 14:44:09
【问题描述】:

我想从日期时间中提取小时/分钟/秒。示例数据框:

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

所以我运行了这段代码,但它在“小时”上增加了一小时?我怎样才能解决这个问题。我想它一定是夏天的东西......

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  

【问题讨论】:

    标签: r dplyr lubridate tibble


    【解决方案1】:

    可能是由于时区元素被剥夺了...让我猜猜:您住在地球的 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 
    

    【讨论】:

    • @温佩尔。非常感谢。是的,我住在 UTC + 1 时区。
    • @Wimpel:我又问了一个新问题link
    【解决方案2】:

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

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

    【讨论】:

    • @arg0naut:谢谢!我不认为格式会起作用。我需要小时/分钟来过滤周五 8 点到 14:30 之间的时间。我稍后会回来,也许在星期一,我现在没有电脑。
    • @arg0naut,我在约会时使用了tz 选项。但它不会转移到使用 lubridate 创建的新变量中。
    • @arg0naut:我问了一个新问题link
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多