如何解析 pyspark 中的推特日期时间字符串?

How to parse twitter date time string in pyspark?

我的数据在 pyspark 数据框中 ('pyspark.sql.dataframe.DataFrame')。其中一列的日期时间以 Twitter 字符串格式存储。

我找到了几个 python 的解决方案,但没有针对 pyspark 的特定解决方案。

这是该列的样子。

+------------------------------+----+
|created_at(string format)     |date|
+------------------------------+----+
|Tue Mar 26 02:29:54 +0000 2019|null|
|Tue Mar 26 02:29:54 +0000 2019|null|
|Tue Mar 26 02:29:54 +0000 2019|null|
|Tue Mar 26 02:29:54 +0000 2019|null|
|Tue Mar 26 02:29:54 +0000 2019|null|
+------------------------------+----+

我尝试了以下解决方案,但没有用

date_df = df.select('created_at', from_unixtime(unix_timestamp('created_at', '%a %b %d %H:%M:%S %z %Y')).alias('date'))

我需要将该列转换为 spark datetime/timestamp 类型,以便我可以执行其他日期时间和在其上的 spark.sql 操作。

我无法获得提供的任​​何解决方案。显然 pyspark.sql 上的 to_timestamp() 函数以某种格式读取输入。所有提供格式的尝试都没有结果。因此使用 UDF(用户定义函数)是不可避免的。但必须注意,该函数不能 return python datetime。所以现在它必须是一个两步过程。

  1. 日期字符串解析UDF,格式转换return为兼容to_timestamp()
  2. 的字符串
  3. 使用to_timestamp()转换spark dataframe中的数据类型
from datetime import datetime
import pytz
from pyspark.sql.functions import udf, to_date, to_utc_timestamp

## Converting date string format
def getDate(x):
    if x is not None:
        return str(datetime.strptime(x,'%a %b %d %H:%M:%S +0000 %Y').replace(tzinfo=pytz.UTC).strftime("%Y-%m-%d %H:%M:%S"))
    else:
        return None

## UDF declaration
date_fn = udf(getDate, StringType())

## Converting datatype in spark dataframe
df = df.withColumn("created_at", to_utc_timestamp(date_fn("created_at"),"UTC")) 

使用SimpleDateFormat构建时间戳格式: 尝试使用以下对我有用的解决方案。

date_df = df.select('created_at', from_unixtime(
    unix_timestamp(col("created_at"),
                        "EEE MMM dd HH:mm:ss ZZZZ yyyy")).alias('date'))

针对 pardeep 的回答,我稍作修改就成功了。

unix_timestamp("created_at", "EEE MMM dd HH:mm:ss Z yyyy")
data_df=spark.createDataFrame([(1,'Mon Oct 05 23:18:25 -0700 2020'),(2,'Tue Oct 06 23:18:25 -0700 2020')], ['srno','created_at'])

data_df.show(2,False)

data_df.printSchema()

date_df = data_df.select('created_at', from_unixtime(unix_timestamp('created_at', 'EEE MMM d HH:mm:ss z yyyy')).alias('date'))

date_df.show(2,False)

We can use to_timestamp function also in place of using unix_timestamp and the from_unixtime.

data_df.select('created_at', to_timestamp('created_at', 'EEE MMM d HH:mm:ss z yyyy').alias('date')).show(2,False)

data_df.select('created_at', from_unixtime(unix_timestamp('created_at', 'EEE MMM d HH:mm:ss z yyyy')).alias('date')).show(2,False)