pyspark to_timestamp 不包括毫秒

Ana*_*ige 5 apache-spark pyspark

我正在尝试将时间戳列格式化为包含毫秒,但没有成功。我怎样才能将我的时间格式化为这样 - 2019-01-04 11:09:21.152

我查看了文档并遵循了 SimpleDataTimeFormat ,pyspark 文档说该to_timestamp函数正在使用它。

这是我的数据框。

+--------------------------+
|updated_date              |
+--------------------------+
|2019-01-04 11:09:21.152815|
+--------------------------+
Run Code Online (Sandbox Code Playgroud)

我使用毫秒格式没有成功,如下所示

>>> df.select('updated_date').withColumn("updated_date_col2", 
to_timestamp("updated_date", "YYYY-MM-dd HH:mm:ss:SSS")).show(1,False)
+--------------------------+-------------------+
|updated_date              |updated_date_col2  |
+--------------------------+-------------------+
|2019-01-04 11:09:21.152815|2019-01-04 11:09:21|
+--------------------------+-------------------+
Run Code Online (Sandbox Code Playgroud)

我希望updated_date_col2格式为2019-01-04 11:09:21.152

小智 2

这不是 to_timestamp 的解决方案,但您可以轻松地将列保持为时间格式

以下代码是将数字毫秒转换为时间戳的示例之一。

from datetime import datetime

ms = datetime.now().timestamp() # ex) ms = 1547521021.83301
df = spark.createDataFrame([(1, ms)], ['obs', 'time'])
df = df.withColumn('time', df.time.cast("timestamp"))
df.show(1, False) 

+---+--------------------------+
|obs|time                      |
+---+--------------------------+
|1  |2019-01-15 12:15:49.565263|
+---+--------------------------+
Run Code Online (Sandbox Code Playgroud)

如果你在 JS 或Python 中使用new Date().getTime()or ,你可以得到一个数值毫秒。Date.now()datetime.datetime.now().timestamp()