scala - 如何在pyspark或scala中将字符串转换为时间数据类型?
问题描述
请注意,我不是在要求unix_timestamp
或timestamp
或datetime
数据类型,而是在要求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
数据类型。
感谢任何建议或帮助。提前致谢。
解决方案
以下是在 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
推荐阅读
- apache-flink - Flink 指标 - 指标间隔内的记录数
- ibm-doors - DOORS DXL 重建主柱
- pandas - 在熊猫数据框中添加额外的缺失组合行
- oracle - 在不合并的情况下重写 Oracle PL/SQL 过程
- python - 从excel文件(熊猫数据框)创建字典
- c - 函数找不到失败的内存分配
- c# - 派生类上的派生属性/字段:容器类及其字段之一上的“继承阶梯”
- android - Activity 销毁时,AnyChartView 出现内存泄漏
- python - 将重复的列从 CSV 转换为嵌套的 BigQuery 表?
- python - 如何让服务器的创建者选择新用户加入服务器的机器人消息将被发送到哪里?