首页 > 解决方案 > 在 Pyspark 中将字符串转换为时间戳对象

问题描述

我正在尝试将字符串转换为 Pyspark 中的时间戳格式。

from pyspark.sql.types import DateType

df = spark.createDataFrame([('28/Mar/2021:06:29:54 -0700',)], ['dt'])
df.select(date_format('dt', 'd/M/y:h:m:s Z').alias('date')).collect()

这似乎不起作用,可能是因为 date_format 函数无法将其识别为有效格式。我明白了:

[行(日期=无)]

无论如何,我可以让 pyspark 函数理解格式,类似于 Python 中的 datetime 模块吗?

from datetime import datetime
datetime.strptime('28/Mar/2021:06:29:54 -0700', '%d/%b/%Y:%H:%M:%S %z')

当我们传递格式时,它会创建一个有效的日期时间对象

datetime.datetime(2021, 3, 28, 6, 29, 54, tzinfo=datetime.timezone(datetime.timedelta(days=-1, seconds=61200)))

标签: pythonapache-sparkdatetimepysparkapache-spark-sql

解决方案


与 Python 日期时间模块不同,在 Spark 中,您需要为每个模式指定字符数。此外,用于to_timestamp将字符串转换为时间戳类型。date_format反之亦然,即将时间戳类型转换为字符串。

from pyspark.sql.functions import to_timestamp

df = spark.createDataFrame([('28/Mar/2021:06:29:54 -0700',)], ['dt'])
df.select(to_timestamp('dt', 'dd/MMM/yyyy:HH:mm:ss Z').alias('date')).collect()
# gives [Row(date=datetime.datetime(2021, 3, 28, 14, 29, 54))]

推荐阅读