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

R:为什么“%b.%Y”日期类不是“date”?

  •  1
  • s__  · 技术社区  · 6 年前

    sep-2018
    

    从这样的日期开始:

    Sys.Date()
    [1] "2018-09-21"
    

    为了得到这个结果,我通常使用:

    format(Sys.Date(),'%b-%Y')
    

    但它 class 不是日期:

     class(format(Sys.Date(),'%b-%Y'))
    [1] "character"
    

    为什么不是约会?有可能和它一起吃吗 class() = date ,怎么办?

    像动物园这样的外部图书馆也有同样的东西。

    library(zoo)
    > class(format(as.yearmon(format(Sys.Date()), "%Y-%m-%d"), "%b.%Y"))
    [1] "character"
    

    同样使用“%m.%Y”似乎会生成相同的内容,但它不会创建(例如)订购问题。

    2 回复  |  直到 6 年前
        1
  •  3
  •   Rohit    6 年前

    format命令获取日期并根据您提供的格式输出可打印的字符串。引用文档:

    An object of similar structure to x containing character representations of the 
    elements of the first argument x in a common format, and in the current 
    locale's encoding.
    

    此外,日期变量在内部存储为数字类型(自1970-01-01以来的天数)

    dput(Sys.Date())
    #structure(17795, class = "Date")
    
    structure(0, class = "Date")
    #[1] "1970-01-01"
    

    因此,要确定日期,需要日、月和年字段。如果这三个都没有,它可能会返回NA或错误。上课时间也差不多。如果没有数据,则可以使用一些伪值,并使用format只打印所需的字段。

        2
  •  1
  •   Francisco Yirá    6 年前

    正如罗希特所说, format 不输出日期对象,而是以您选择的格式输出字符串。

    从字符串中获取日期对象,如 "sep-2018" 你可以用 readr::parse_date()

    (my_date <- readr::parse_date("sep-2018", format = '%b-%Y'))
    #[1] "2018-09-01"
    
    class(my_date)
    #[1] "Date"