【问题标题】:How to convert string to time datatype in pyspark or scala?如何在pyspark或scala中将字符串转换为时间数据类型?
【发布时间】:2020-01-07 04:16:53
【问题描述】:

请注意,我要求的不是unix_timestamptimestampdatetime 数据类型我要求的是time 数据类型,在pyspark 或scala 中是否可行?

让我们详细了解一下, 我有一个这样的数据框,列 Time 字符串类型

+--------+
|    Time|
+--------+
|10:41:35|
|12:41:35|
|01:41:35|
|13:00:35|
+--------+

我想将其转换为 time 数据类型,因为在我的 SQL 数据库中,此列是 time 数据类型,所以我尝试使用应用 Bulk Copy 的 spark 连接器插入我的数据 因此,对于批量复制,我的数据框和数据库表架构必须相同,这就是为什么我需要将我的 Timecolumn 转换为 time 数据类型。

感谢任何建议或帮助。提前致谢。

【问题讨论】:

    标签: scala pyspark type-conversion azure-databricks pyspark-dataframes


    【解决方案1】:

    以下是在 PySpark shell 中运行的,datetime 模块确实允许时间格式

    >>> t = datetime.datetime.strptime('10:41:35', '%H:%M:%S').time()
    >>> type(t)
    <class 'datetime.time'>
    

    当使用地图将上述函数应用于数据帧时,它会失败,因为 PySpark 没有数据类型 time 并且无法推断它。

    >>> df2.select("val11").rdd.map(lambda x: datetime.datetime.strptime(str(x[0]), '%H:%M:%S').time()).toDF()
    
    TypeError: Can not infer schema for type: <class 'datetime.time'>
    

    pyspark.sql.types 模块目前仅支持以下数据类型

    NullType
    StringType
    BinaryType
    BooleanType
    DateType
    TimestampType
    DecimalType
    DoubleType
    FloatType
    ByteType
    IntegerType
    LongType
    ShortType
    ArrayType
    MapType
    StructField
    StructType
    

    【讨论】:

      【解决方案2】:

      试试看

      df.withColumn('time', F.from_unixtime(F.unix_timestamp(F.col('time'), 'HH:mm:ss'), 'HH:mm:ss'))
      

      【讨论】:

        猜你喜欢
        • 2021-12-01
        • 1970-01-01
        • 2023-04-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多