在 pyspark 中从时间戳转换为特定日期

Convert from timestamp to specific date in pyspark

我想在特定列上转换特定日期的时间戳。

这是我的输入:

+----------+
| timestamp|
+----------+
|1532383202|
+----------+

我的期望:

+------------------+
|      date        |
+------------------+
|24/7/2018 1:00:00 |
+------------------+

如果可能的话,我想把分和秒都设为0,即使它不是0。

例如,如果我有这个:

+------------------+
|      date        |
+------------------+
|24/7/2018 1:06:32 |
+------------------+

我想要这个:

+------------------+
|      date        |
+------------------+
|24/7/2018 1:00:00 |
+------------------+

我试过的是:

from pyspark.sql.functions import unix_timestamp

table = table.withColumn(
    'timestamp',
    unix_timestamp(date_format('timestamp', 'yyyy-MM-dd HH:MM:SS'))
)

但是我有NULL。

也许您可以使用日期时间库将时间戳转换为您想要的格式。您还应该使用用户定义的函数来处理 spark DF 列。这是我会做的:

# Import the libraries
from pyspark.sql.functions import udf
from datetime import datetime

# Create a function that returns the desired string from a timestamp 
def format_timestamp(ts):
    return datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:00:00')

# Create the UDF
format_timestamp_udf = udf(lambda x: format_timestamp(x))

# Finally, apply the function to each element of the 'timestamp' column
table = table.withColumn('timestamp', format_timestamp_udf(table['timestamp']))

希望对您有所帮助。

更新

受@Tony Pellerin 的回答启发,我意识到您可以直接转到 :00:00 而无需使用 regexp_replace():

table = table.withColumn("date", f.from_unixtime("timestamp", "dd/MM/yyyy HH:00:00"))
table.show()
#+----------+-------------------+
#| timestamp|               date|
#+----------+-------------------+
#|1532383202|23/07/2018 18:00:00|
#+----------+-------------------+

您的代码无效,因为 pyspark.sql.functions.unix_timestamp() 将:

Convert time string with given pattern (‘yyyy-MM-dd HH:mm:ss’, by default) to Unix time stamp (in seconds), using the default timezone and the default locale, return null if fail.

你实际上想做这个操作的逆操作,即convert from an integer timestamp to a string. For this you can use pyspark.sql.functions.from_unixtime():

import pyspark.sql.functions as f

table = table.withColumn("date", f.from_unixtime("timestamp", "dd/MM/yyyy HH:MM:SS"))
table.show()
#+----------+-------------------+
#| timestamp|               date|
#+----------+-------------------+
#|1532383202|23/07/2018 18:07:00|
#+----------+-------------------+

现在 date 列是一个字符串:

table.printSchema()
#root
# |-- timestamp: long (nullable = true)
# |-- date: string (nullable = true)

所以可以用pyspark.sql.functions.regexp_replace()让分秒归零:

table.withColumn("date", f.regexp_replace("date", ":\d{2}:\d{2}", ":00:00")).show()
#+----------+-------------------+
#| timestamp|               date|
#+----------+-------------------+
#|1532383202|23/07/2018 18:00:00|
#+----------+-------------------+

正则表达式模式 ":\d{2}" 表示匹配文字 : 后跟恰好 2 位数字。