【问题标题】:Sparklyr - Changing date format in SparkSparklyr - 在 Spark 中更改日期格式
【发布时间】:2018-01-11 12:44:03
【问题描述】:

我有一个 Spark 数据框,其列 characters 为 20/01/2000(日/月/年)。

但我正在尝试将其更改为日期格式,因此我可以在这里使用函数:https://cwiki.apache.org/confluence/display/Hive/LanguageManual+UDF#LanguageManualUDF-DateFunctions 仅获取我想要的数据(例如提取月份和日期)。

但似乎这些功能仅在我使用其他格式的日期时才有效,例如 1970-01-30。

一个例子:

sc <- spark_connect(master = "spark://XXXX")
df <- data.frame(date = c("20/10/2010", "19/11/2010"))
df_tbl <- copy_to(sc, df, "df")

如果我只想在新列中提取月份:

df_tbl <- df_tbl %>% mutate(month = month(date))

我明白了:

> df_tbl %>% glimpse()
Observations: 2
Variables: 2
$ data  <chr> "20/10/2010", "19/11/2010"
$ month <int> NA, NA

由于 R 的函数 as.Date() 不起作用,我不得不使用另一个工具。

有什么线索吗?

【问题讨论】:

    标签: r date apache-spark sparklyr


    【解决方案1】:

    正如已经弄清楚的那样,这失败了,因为19/11/2010 不是可接受的日期格式。在 Spark 2.2 或更高版本中,您可以:

    df_tbl %>% mutate(month = month(to_date(date, "dd/MM/yyyy")))
    
    # # Source:   lazy query [?? x 2]
    # # Database: spark_connection
    #   date       month
    #    <chr>      <int>
    # 1 20/10/2010    10
    # 2 19/11/2010    11
    

    在 2.1 或之前:

    df_tbl %>% 
      mutate(month = month(from_unixtime(unix_timestamp(date, "dd/MM/yyyy"))))
    
    # # Source:   lazy query [?? x 2]
    # # Database: spark_connection
    #   date       month
    #   <chr>      <int>
    # 1 20/10/2010    10
    # 2 19/11/2010    11
    

    单独格式化:

    df_tbl %>%  
       mutate(formatted = from_unixtime(
         unix_timestamp(date, "dd/MM/yyyy"), "dd-MM-yyy"))
    
    # # Source:   lazy query [?? x 2]
    # # Database: spark_connection
    #   date       formatted 
    #   <chr>      <chr>     
    # 1 20/10/2010 20-10-2010
    # 2 19/11/2010 19-11-2010
    

    【讨论】:

      【解决方案2】:

      sparklyr 还不支持列类型日期。

      【讨论】:

        【解决方案3】:

        您也许可以使用 Hive(这是 Spark SQL 所基于的)定义的函数来完成此操作,请参阅:https://spark.rstudio.com/articles/guides-dplyr.html#hive-functions

        【讨论】:

          猜你喜欢
          • 2021-09-14
          • 2010-10-12
          • 2013-06-03
          • 2015-03-03
          • 2011-11-18
          • 2022-01-28
          • 2014-10-23
          • 2016-11-18
          • 1970-01-01
          相关资源
          最近更新 更多