【问题标题】:How can I test if 2 datetimes represent the same clock time (ignoring the date) in R?如何测试 2 个日期时间是否代表 R 中的相同时钟时间(忽略日期)?
【发布时间】:2020-11-28 03:16:48
【问题描述】:

在 R 中,我有 2 个 POSIXct(即日期+时间)向量,我想测试它们是否代表相同的时钟时间,无论日期如何。例如:

library(lubridate)
# 1:12:57 PM in NYC
dttm1 <- ymd_hms("1993-10-15 13:12:57", tz = "America/New_York")
# Also 1:12:57 PM in NYC, on a different day
dttm2 <- ymd_hms("2007-2-27 17:12:57", tz = "UTC")
# 1:12:57 PM, but not in NYC
dttm3 <- ymd_hms("2007-2-27 13:12:57", tz = "UTC")
# Not 1:12:57 PM in any time zone
dttm4 <- ymd_hms("1963-1-15 01:12:57", tz = "UTC")

是否有一个函数可以告诉我这些日期时间中的哪一个代表相同的时钟时间?对于dttm1dttm2,这样的函数应该返回TRUE,而对于上述任何其他日期对,应该返回FALSE。理想情况下,该函数将被矢量化以在日期时间向量上按元素工作。如果这样的功能仅适用于同一时区的日期时间,或者需要指定应该执行比较的时区,那就没问题了。 (对于奖励积分,仅对 dttm1dttm3 返回 TRUE 的第二个函数也很好。)

【问题讨论】:

    标签: r datetime time


    【解决方案1】:

    我必须在这里重新发明轮子,但你可以这样做:

    utc_time <- function(x, convert = TRUE) {
     if (convert) x <- as.POSIXct(as.numeric(x), origin = "1970-01-01", tz = "UTC")
     substr(x, 12, 19)
    }
    

    所以默认情况下,您将 UTC 转换的时间作为字符串获取

    utc_time(dttm1)
    #> [1] "17:12:57"
    
    utc_time(dttm2)
    #> [1] "17:12:57"
    
    utc_time(dttm1) == utc_time(dttm2)
    #> [1] TRUE
    
    utc_time(dttm3)
    #> [1] "13:12:57"
    
    utc_time(dttm3) == utc_time(dttm1)
    #> [1] FALSE
    

    但如果您想要转换日期时间的选项,请指定convert = FALSE

    utc_time(dttm1, convert = FALSE) == utc_time(dttm3, convert = FALSE)
    #> [1] TRUE
    

    【讨论】:

      【解决方案2】:

      你也可以这样做:

      mytime <- function(x)  as.numeric(x) %% 86400
      
      mytime(dttm1) == mytime(c(dttm2,dttm3, dttm4))
      
      [1]  TRUE FALSE FALSE
      

      【讨论】:

      • 我不希望函数为 dttm1dttm3 返回 TRUE。 (我在括号中要求一个 separate 函数来执行此操作。)
      猜你喜欢
      • 2012-06-20
      • 1970-01-01
      • 2018-01-25
      • 2017-12-07
      • 2013-03-01
      • 2012-10-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多