
[英]How to convert a weird date time string with timezone into a timestamp (PySpark)
[英]How to convert String to Time in PYSPARK?
我试图将字符串转换为时间,但得到 NULL。
例如,val Start =='080000'
使用以下步骤,
1)unix_timestamp(col('Start'),'HH:mm:ss'),\
2)to_timestamp(lit('Start'),'HH:mm:ss'),\
3)to_timestamp(col('Start'),'HH:mm:ss'),\
4)from_unixtime(unix_timestamp(col('Start'),'HH:mm:ss'))
预期 Output:
08:00:00 (HH:MM:SS)
有人可以建议方法吗
Spark 确实有TimeType
。 最新版本 v3.1.1 只有DateType
和TimestampType
,因此您的请求将 String 转换为 Time 的简单答案是不可能的。
但是,可以从080000
(StringType) 转换为2000-01-01 08:00:00
(TimestampType) – 或任何日期,因为日期无关紧要 – 您可以执行任何类型的日期比较
(df
.withColumn('from_timestamp', F.regexp_replace(F.col('from'), '(\d{2})(\d{2})(\d{2})', '2000-01-01 $1:$2:$3'))
.withColumn('to_timestamp', F.regexp_replace(F.col('to'), '(\d{2})(\d{2})(\d{2})', '2000-01-01 $1:$2:$3'))
.withColumn('diff', F.to_timestamp(F.col('to_timestamp')) - F.to_timestamp(F.col('from_timestamp')))
.show()
)
# +------+------+-------------------+-------------------+----------+
# | from| to| from_timestamp| to_timestamp| diff|
# +------+------+-------------------+-------------------+----------+
# |080000|083000|2000-01-01 08:00:00|2000-01-01 08:30:00|30 minutes|
# +------+------+-------------------+-------------------+----------+
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.