首页 > 解决方案 > 如何在pyspark或scala中将字符串转换为时间数据类型?

问题描述

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

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

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

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

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

标签: scalapysparktype-conversionazure-databrickspyspark-dataframes

解决方案


以下是在 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

推荐阅读