2017-08-02 110 views
-1

我正在使用spark 2.1.0。我无法在pyspark中创建时间戳列,我正在使用下面的代码段。请帮助Pyspark创建时间戳列

df=df.withColumn('Age',lit(datetime.now())) 

我越来越

assertion error:col should be Column

请帮

回答

2

假设您从您的代码段有数据框中,你想对所有的行相同的时间戳。

让我创建一些虚拟数据框。

>>> dict = [{'name': 'Alice', 'age': 1},{'name': 'Again', 'age': 2}] 
>>> df = spark.createDataFrame(dict) 

>>> import time 
>>> import datetime 
>>> timestamp = datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S') 
>>> type(timestamp) 
<class 'str'> 

>>> from pyspark.sql.functions import lit,unix_timestamp 
>>> timestamp 
'2017-08-02 16:16:14' 
>>> new_df = df.withColumn('time',unix_timestamp(lit(timestamp),'yyyy-MM-dd HH:mm:ss').cast("timestamp")) 
>>> new_df.show(truncate = False) 
+---+-----+---------------------+ 
|age|name |time     | 
+---+-----+---------------------+ 
|1 |Alice|2017-08-02 16:16:14.0| 
|2 |Again|2017-08-02 16:16:14.0| 
+---+-----+---------------------+ 

>>> new_df.printSchema() 
root 
|-- age: long (nullable = true) 
|-- name: string (nullable = true) 
|-- time: timestamp (nullable = true)