代码之家  ›  专栏  ›  技术社区  ›  rbatt

如何为R中的3个字母tz指定POSIX(时间)格式,以便忽略它?

  •  5
  • rbatt  · 技术社区  · 11 年前

    对于输出,规格为 %Z (参见 ?strptime ). 但对于输入,这是如何工作的?

    为了澄清这一点,最好将时区缩写解析为有用的信息 as.POSIXct() ,但更核心的问题是如何使函数至少忽略时区。

    这是我最好的解决方法,但是否有特定的格式代码要传递给 作为.POSIXct() 这对所有时区都有效吗?

    times <- c("Fri Jul 03 00:15:00 EDT 2015", "Fri Jul 03 00:15:00 GMT 2015")
    as.POSIXct(times, format="%a %b %d %H:%M:%S %Z %Y") # nope! strptime can't handle %Z in input
    
    formats <- paste("%a %b %d %H:%M:%S", gsub(".+ ([A-Z]{3}) [0-9]{4}$", "\\1", times),"%Y")
    as.POSIXct(times, format=formats) # works
    

    编辑:这是最后一行的输出,以及它的类(来自单独的调用);输出如预期。从控制台:

    > as.POSIXct(times, format=formats)
    [1] "2015-07-03 00:15:00 EDT" "2015-07-03 00:15:00 EDT"
    
    > attributes(as.POSIXct(times, format=formats))
    $class
    [1] "POSIXct" "POSIXt" 
    
    $tzone
    [1] ""
    
    1 回复  |  直到 11 年前
        1
  •  4
  •   Joshua Ulrich    11 年前

    简短的回答是,“不,你不能。”这些都是缩写,不能保证它们能唯一标识特定的时区。

    例如,“EST”东部标准时间是在美国还是澳大利亚?“CST”是美国或澳大利亚的中央标准时间,还是中国标准时间,抑或古巴标准时间?


    我只是注意到,你并没有试图解析时区缩写,你只是试图避免它。我不知道该怎么说 strptime 忽略任意字符。我知道它将忽略格式字符串结束后时间的字符表示中的任何内容。例如:

    R> # The year is not parsed, so the current year is used
    R> as.POSIXct(times, format="%a %b %d %H:%M:%S")
    [1] "2015-07-03 00:15:00 UTC" "2015-07-03 00:15:00 UTC"
    

    除此之外,正则表达式是我唯一能想到的解决这个问题的方法。与您的示例不同,我将使用输入字符向量上的正则表达式来删除所有3-5个字符的时区缩写。

    R> times_no_tz <- gsub(" [[:upper:]]{3,5} ", " ", times)
    R> as.POSIXct(times_no_tz, format="%a %b %d %H:%M:%S %Y")
    [1] "2015-07-03 00:15:00 UTC" "2015-07-03 00:15:00 UTC"
    
    推荐文章