Pyspark from_unixtime(unix_timestamp)不会转换为时间戳

时间:2019-01-24 01:07:39

标签: date pyspark

我正在将Pyspark与Python 2.7结合使用。我在字符串中有一个日期列(带有ms),并且想要转换为时间戳

这是我到目前为止尝试过的

df = df.withColumn('end_time', from_unixtime(unix_timestamp(df.end_time, '%Y-%M-%d %H:%m:%S.%f')) )

printSchema()显示 end_time: string (nullable = true)

我将时间戳记用作变量的类型

4 个答案:

答案 0 :(得分:1)

尝试使用from_utc_timestamp

from pyspark.sql.functions import from_utc_timestamp

df = df.withColumn('end_time', from_utc_timestamp(df.end_time, 'PST')) 

您需要为函数指定时区,在这种情况下,我选择了PST

如果这不起作用,请给我们举几行显示df.end_time

的示例

答案 1 :(得分:0)

创建一个时间戳格式为字符串的示例数据框:

import pyspark.sql.functions as F
df = spark.createDataFrame([('22-Jul-2018 04:21:18.792 UTC', ),('23-Jul-2018 04:21:25.888 UTC',)], ['TIME'])
df.show(2,False)
df.printSchema()

输出:

+----------------------------+
|TIME                        |
+----------------------------+
|22-Jul-2018 04:21:18.792 UTC|
|23-Jul-2018 04:21:25.888 UTC|
+----------------------------+
root
|-- TIME: string (nullable = true)

字符串时间格式(包括毫秒)转换为 unix_timestamp(double)由于unix_timestamp()函数不包含毫秒,因此我们需要使用另一种简单的技巧将其添加,以包含毫秒。使用子字符串方法(start_position = -7,length_of_substring = 3)从字符串中提取毫秒,并分别向unix_timestamp添加毫秒。 (投射到子字符串以使其浮动以进行添加)

df1 = df.withColumn("unix_timestamp",F.unix_timestamp(df.TIME,'dd-MMM-yyyy HH:mm:ss.SSS z') + F.substring(df.TIME,-7,3).cast('float')/1000)

在Spark中将 unix_timestamp(double)转换为 timestamp数据类型

df2 = df1.withColumn("TimestampType",F.to_timestamp(df1["unix_timestamp"]))
df2.show(n=2,truncate=False)

这将为您提供以下输出

+----------------------------+----------------+-----------------------+
|TIME                        |unix_timestamp  |TimestampType          |
+----------------------------+----------------+-----------------------+
|22-Jul-2018 04:21:18.792 UTC|1.532233278792E9|2018-07-22 04:21:18.792|
|23-Jul-2018 04:21:25.888 UTC|1.532319685888E9|2018-07-23 04:21:25.888|
+----------------------------+----------------+-----------------------+

检查架构:

df2.printSchema()


root
 |-- TIME: string (nullable = true)
 |-- unix_timestamp: double (nullable = true)
 |-- TimestampType: timestamp (nullable = true)

答案 2 :(得分:0)

在当前版本的spark中,关于时间戳转换,我们不必做太多事情。

在这种情况下,使用to_timestamp函数效果很好。我们唯一需要注意的是根据原始列输入时间戳的格式。 在我的情况下,格式为yyyy-MM-dd HH:mm:ss。 其他格式可以是MM / dd / yyyy HH:mm:ss或类似的组合。

from pyspark.sql.functions import to_timestamp
df=df.withColumn('date_time',to_timestamp('event_time','yyyy-MM-dd HH:mm:ss'))
df.show()

答案 3 :(得分:-1)

以下内容可能会有所帮助:-

from pyspark.sql import functions as F
df = df.withColumn("end_time", F.from_unixtime(F.col("end_time"), 'yyyy-MM-dd HH:mm:ss.SS').cast("timestamp"))

[已更新]

相关问题