gpt4 book ai didi

python - pyspark Dataframe API cast ('timestamp' ) 不适用于时间戳字符串

转载 作者:行者123 更新时间:2023-11-28 21:09:28 24 4
gpt4 key购买 nike

我有这样的数据:

{"id":1,"createdAt":"2016-07-01T16:37:41-0400"}
{"id":2,"createdAt":"2016-07-01T16:37:41-0700"}
{"id":3,"createdAt":"2016-07-01T16:37:41-0400"}
{"id":4,"createdAt":"2016-07-01T16:37:41-0700"}
{"id":5,"createdAt":"2016-07-06T09:48Z"}
{"id":6,"createdAt":"2016-07-06T09:48Z"}
{"id":7,"createdAt":"2016-07-06T09:48Z"}

我正在将 createdAt 字段转换为时间戳,如下所示。

from pyspark.sql import SQLContext
from pyspark.sql.functions import *

sqlContext = SQLContext(sc)
df = sqlContext.read.json('data/test.json')
dfProcessed = df.withColumn('createdAt', df.createdAt.cast('timestamp'))

dfProcessed.printSchema()
dfProcessed.collect()

我得到的输出如下。我得到了 createdAt 的 None 值。我该怎么做才能将字段检索为正确的时间戳?

root
|-- createdAt: timestamp (nullable = true)
|-- id: long (nullable = true)

[Row(createdAt=None, id=1),
Row(createdAt=None, id=2),
Row(createdAt=None, id=3),
Row(createdAt=None, id=4),
Row(createdAt=None, id=5),
Row(createdAt=None, id=6),
Row(createdAt=None, id=7)]

最佳答案

为了简单地将字符串列转换为时间戳,字符串列的格式必须正确。

要检索“createdAt”列作为时间戳,您可以编写将转换字符串的 UDF 函数

"2016-07-01T16:37:41-0400"

"2016-07-01 16:37:41"

并将“createdAt”列转换为新格式(不要忘记处理时区字段)。

一旦您有一个包含时间戳作为字符串(如“2016-07-01 16:37:41”)的列,一个简单的转换为时间戳就可以完成这项工作,就像您在代码中一样。

您可以阅读更多关于 Spark 中的日期/时间/字符串处理的信息 here .

关于python - pyspark Dataframe API cast ('timestamp' ) 不适用于时间戳字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38285099/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com